乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      C# 實(shí)例:重寫(override)

       ontheroad96j47 2021-11-08

      1、重寫(override):子類中為滿足自己的需要來重復(fù)定義某個(gè)方法的不同實(shí)現(xiàn),需要用 override 關(guān)鍵字,被重寫的方法必須是虛方法,用的是 virtual 關(guān)鍵字。它的特點(diǎn)是(三個(gè)相同):

      • 相同的方法名

      • 相同的參數(shù)列表

      • 相同的返回值

      如:父類中的定義:

      public virtual void EatFood()
      {
      Console.WriteLine("Animal吃東西");
      }

      子類中的定義:

      public override void EatFood()
      {
      Console.WriteLine("Cat吃東西");
      //base.EatFood();
      }

      小提示:經(jīng)常有童鞋問重載和重寫的區(qū)別,而且網(wǎng)絡(luò)上把這兩個(gè)的區(qū)別作為 C# 做??嫉拿嬖囶}之一。實(shí)際上這兩個(gè)概念完全沒有關(guān)系,僅僅都帶有一個(gè)"重"字。他們沒有在一起比較的意義,僅僅分辨它們不同的定義就好了。

      3、虛方法:即為基類中定義的允許在派生類中重寫的方法,使用virtual關(guān)鍵字定義。如:

      public virtual void EatFood()
      {
          
      Console.WriteLine("Animal吃東西");
      }

      注意:虛方法也可以被直接調(diào)用。如:

      Animal a = new Animal();
      a
      .EatFood();

      執(zhí)行輸出結(jié)果為:

      Animal吃東西

      完整代碼:

      using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;
      namespace WindowsFormsApp4{ public partial class Form1 : Form { public Form1() { InitializeComponent(); }
      private void Form1_Load(object sender, EventArgs e) {
      }
      private void button1_Click(object sender, EventArgs e) { test2 t2 = new test2(); t2.EatFood();
      test1 t1 = new test1();//虛方法也可以被直接調(diào)用 t1.EatFood(); } }
      // 對于類來說,如果你沒有寫訪問修飾符,那么是internal的,只有程序集內(nèi)部可以訪問! //對于類的成員(字段, 屬性, 方法等),如果你沒有寫訪問修飾符,那么是private的! class test1 { public virtual void EatFood() //父類中的定義:基類中定義的允許在派生類中重寫的方法,使用virtual關(guān)鍵字定義 { MessageBox.Show("Animal吃東西"); }
      } partial class test2 : test1 { public override void EatFood() // 子類中的定義:子類中為滿足自己的需要來重復(fù)定義某個(gè)方法的不同實(shí)現(xiàn) { MessageBox.Show("Cat吃東西"); //base.EatFood(); } }
      }


      運(yùn)行結(jié)果:

        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多