總目錄
C# 語法總目錄
系列鏈接
C# 面向對象編程(一) ????類 第一篇
C# 面向對象編程(一) ????類 第二篇
C# 面向對象編程(一) ????類 第三篇
C# 面向對象編程 一 ——類 第三篇
- 簡介
- 面向對象編程
- 類 第三篇
- 9. 重載運算符
- 10. 分部方法
- ** nameof方法 **
- ** GetType 方法和 typeof方法 **
- ** ToString方法 **
- 結構體
簡介
??主要記錄的是面向對象編程中,類重載運算符,分部方法的使用和一些常用方法,以及結構體的一些注意事項
面向對象編程
類 第三篇
9. 重載運算符
internal class PersonIntroduce
{private int a;public int A { get => a; set => a = value; }public PersonIntroduce(){a = 1;}~PersonIntroduce(){Console.WriteLine("結束了");}public static PersonIntroduce operator +(PersonIntroduce a, PersonIntroduce b){PersonIntroduce per = new PersonIntroduce();per.a = a.a + b.a;return per;}
}
static void Main(string[] args)
{PersonIntroduce pi = new PersonIntroduce();PersonIntroduce pj = new PersonIntroduce();Console.WriteLine((pi + pj).A); }
//輸出
2
10. 分部方法
方法的聲明和定義可以在不同文件里面,但是需要再同一個命名空間,添加 partial 關鍵字
partial class PersonIntroduce
{partial void Add();
}
partial class PersonIntroduce
{ partial void Add(){}
}
** nameof方法 **
可以返回任意類型或者成員或者變量的字符串名稱
Person p = new Person();
string name = nameof(p); //輸出 pint num = 10;
string name = nameof(num); //輸出 num
** GetType 方法和 typeof方法 **
使用這個兩個方法可以獲取當前對象的類,兩個都是返回的 System.Type 類型
Dog dog = new Dog();
Console.WriteLine(dog.GetType() == typeof(Dog));
** ToString方法 **
可以在類中重寫該方法
結構體
結構體和類相比,結構體是值類型,類是引用類型。結構體無法繼承。
結構體可以包含:
- 字段初始化器
- 無參數的構造器
- 終結器
- 虛成員或 protected 成員
public struct Point{int x,y;public Point(int x,int y){ this.x = x; this.y = y;}
}
總目錄
C# 語法總目錄
系列鏈接
C# 面向對象編程(一) ????類 第一篇
C# 面向對象編程(一) ????類 第二篇
C# 面向對象編程(一) ????類 第三篇