1:封裝
將對象進行封裝,並不等於將整個對象完全包裹起來,而是根據實際需要,設置一定的訪問權限,用戶根據不同的權限調用對象提供的功能,在C#語言中,可以使用修飾符public、internal、protected、private分別修飾類的字段、屬性和方法。
2:繼承,主要是注意繼承的格式
- public class ParentClass //父類
- {
- public ParentClass();
- }
- public class ChildClass : ParentClass :子類
- {
- public ChildClass();
- }
3:多態
多態是面向對象編程思想的核心之一,多態的意思是:當從父類派生出了一些子類后,每個子類都由不同的代碼實現,因此,同樣的調用可以產生不同的效果,主要由子類來決定,在程序運行時,面向對象的語言會自動判斷對象的派生類型,並調用相應的方法。
在C#中多態分為兩種類型,即編譯時多態和運行時多態,編譯時多態是通過重載來實現的,運行時多態是系統運行時根據實際情況來決定何種操作。
實例代碼:
- public class MyIntertest
- {
- public virtual void interest()
- {
- Console.WriteLine("我的愛好");
- Console.ReadLine();
- }
- }
- public class Writer : MyIntertest
- {
- public override void Interest()
- {
- Console.WriterLine("寫作");
- }
- }
- public class Program : MyInterest
- {
- public override void interest()
- {
- Console.WriteLine("編程");
- }
- }
- public class Sing : MyInterest
- {
- public override void interest()
- {
- Console.WriteLine("唱歌");
- }
- }
- public class Test
- {
- public static int main(String[] args)
- {
- MyInterest[] interests = new MyInterest[4];
- interests[0] = new Write();
- interests[1] = new Program();
- interests[2] = new Sing();
- interests[3] = new MyInterest()
- foreach ( MyInterest interest in interests)
- {
- interest.interest();
- }
- return 0;
- }
- }
4:
接口: 界面,是兩個有界事物的交界處,通過界面可以與對方交互,交互的方式由約定產生,這種約定就是由具體交互動作的規則,只要遵循規則 即可與擁有規則的事物交互。 在C#中,接口是聲明類具有的方法和成員的、自身不能被實例化的、只能被繼承的特殊的類,其只管描述事物的特性而實現特性的任務卻由其他類負責。 接口中不能包含字段 接口定義了類要實現的一系列方法,但是它本身不能實現這些方法,只是用邏輯結構方式來描述。 在接口的成員中,只能是方法、屬性、事件或者索引器,它的成員不能包含常數、字段、運算符、實例構造函數、析構構造函數或類型,也不能包含任意種類的 靜態成員。
- interface MyInterface
- {
- string STR //屬性STR
- {
- get; //屬性可讀
- set; //屬性可寫
- }
- void outMethod(); //成員方法outMethod
- }
- class InheritInterface : MyInterface
- {
- string str = "21天學習C#"; //定義並初始化字符串
- public string STR
- {
- get
- {
- return str;
- }
- set
- {
- str = value;
- }
- }
- public void outMethod()
- {
- Console.WriteLine(this.STR);
- }
- }
5: 域和屬性 域也叫成員變量,它可以用來保存類的各種信息,域可以分為靜態域和實例域兩種,其中,靜態域屬於類,實例域屬於對象。 屬性是一種用來訪問對象的特殊成員。 域的聲明:和普通變量相同,可以用new, public, protected, static和readonly等
- public class Date
- {
- private string name = "hoan";
- public string nameAttr
- {
- get //使用get訪問器讀值
- {
- return name;
- }
- set //使用set訪問器寫值
- {
- }
- }
- }
6:匿名方法:
匿名方法的作用是將代碼塊當作參數來使用,使代碼對於委托的實例很直接,很便利,可以減少實例化委托對系統資源的開銷。匿名方法還共享了
本地語句包含的函數成員訪問權限。
匿名方法的使用:
- namespace codemo
- {
- delegate void Writer(string s); //委托所調用的命名方法
- class Program
- {
- static void NamedMethod(string k) //委托所調用的命名方法
- {
- System.Console.WriteLine(k);
- }
- static void Main(string[] args)
- {
- Writer w = delegate(string j) //委托類調用匿名方法
- {
- System.Console.WriteLine(j);
- }
- w("調用了匿名方法");
- Console.WriteLine();
- w = new Writer(NamedMethod); //創建對象
- w("調用了命名方法"); //調用命名方法
- Console.ReadLine();
- }
- }
- }