Class:
- class是blueprint,用來描述What kinds of data the object holds and works with, What the object can do what its functionality is
- Usually, your C# programs will define their own classes, as well as use the classes that are provided by the .NET framework
- Class define two major things(Fields and Properties & Methords)
- Class can inherit attribute and methords from other clas
- Define class:
class myClass{//fields to contain the class dataint myInteger;string myMessage;//methords that define the class functionalitypublic int myFunction() {return myInteger;//whatever other logic there is}public myClass(string defaultMsg) {myMessage = defaultMsg;//這個是constructor, 一般用來給fileds賦值的}}
6: Use Class: 使用執行個體.方法
使用new來建立類的執行個體
myClass myObj = new myClass("Hello");
7: 使用類的fields和方法用"."
int myResult = myObj.AddNumber(5, 10);
8:Static: 使用類名.方法
Console.WriteLine("Hello World");
9:Instance member VS Static member:
1 namespace DefiningAClass 2 { 3 class MyClass{ 4 int myIntegar; 5 string meMessage; 6 public static int myStaticInt = 100; //static variable 7 8 public int myFunction() { //instance member function 9 return myIntegar;10 }11 12 public MyClass() { //Constructor use to initial fields13 myIntegar = 50;14 meMessage ="This is made from constructor"15 }16 }17 class Program18 {19 static void Main(string[] args)20 {21 MyClass myC = new MyClass(); //調用Constructor22 Console.WriteLine("Calling instance member function : {0}", myC.myFunction()); //使用instance member23 Console.WriteLine("Calling static variable : {0}", MyClass.myStaticInt); //使用static member24 Console.ReadLine();25 }26 }27 }
10:Access Modifier:
Private:只可class itself訪問
Public: 可以被其他object訪問
protected:可以class itself和整合的subclass訪問
internal:can be accessed by any class in the same assembly(package of code like a library or other program)
eg:
Wine.csnamespace AccessModifier //注意建立的新類Wine被放在以project名字的NS下{ class Wine { public string Name; public decimal Price; private string Description; protected decimal dicount; public Wine(string wineName, decimal winePrice) { Name = wineName; Price = winePrice; dicount = 0.0m; } }}
Program.csnamespace AccessModifier{ class Program { static void Main(string[] args) { Wine myWine = new Wine("Jacky", 100); myWine.Name = "ZXX"; myWine.Price = 200m; } }}
Property:
- property 就像field只不過他還有背後的邏輯
- 從外部看,他們像是成員變數,但是表現上像成員函數
- 定義像field,內部包含get,set, get裡即把什麼數值return給調用property的使用者, set就是用一個value來set一個private變數,getter,setter實際就是兩個簡寫的方法。
- property是典型使用puiblic的情況,其他還有Methord,和Event,其他類型一般都是private或者sealed,protected。
- property可以是唯讀或者唯寫
好處
- 對於使用property的人來說實現了邏輯封裝,使用者不必知道property內部實現了什麼樣的邏輯,只需要用就好了。
- property的內部邏輯變化了,外部使用不變,也不用關心。
- property的get,set可以有邏輯在裡面,判斷值。
比如: