一般咱們須要對class的相加,相減,相乘 等重載以適應需求, 如caml查詢的時候,咱們能夠定義一個caml類,而後來操做這些查詢.
首先,咱們定義一個class爲Test
public class Test
而後定義兩個成員,一個int類型的ID,一個字符串類型的Name.ide
public int ID; public string Name;
而後定義構造函數函數
public Test() { } public Test(int id) { this.ID = id; } public Test(int id, string name) { this.ID = id; this.Name = name; }
重載兩個class相加的運算符,測試
public static Test operator +(Test t1, Test t2) { if (t2.Name!= null) { return new Test(t1.ID + t2.ID, t1.Name + t2.Name); } else { return new Test(t1.ID + t2.ID); } }
重載兩個class的|運算,其餘的運算符如(-,*,/,&)你們能夠本身去試試.ui
public static Test operator |(Test t1, Test t2) { //顯示ID大的class return new Test(t1.ID > t2.ID ? t1.ID:t2.ID); }
下面寫了一個對Test這個class的擴展方法,相等於這個class自帶的成員方法. 擴展返回發的寫法關鍵是this 後面帶類型和參數this
internal static class Util { public static string Format(this Test t) { StringBuilder sb = new StringBuilder(); if (t.ID != null) { sb.AppendLine("ID:"+t.ID.ToString()); } if (!string.IsNullOrEmpty(t.Name)) { sb.AppendLine("Name:" + t.Name.ToString()); } return sb.ToString(); } }
調用這個方法:spa
class Program { static void Main(string[] args) { //測試兩個class相加 Test test1 = new Test(1); Test test2 = new Test(2); Console.WriteLine("兩個class相加的結果爲:"+(test1 +test2).Format()); Console.WriteLine("兩個class比較值大的結果爲:" + (test1 |test2).Format()); } }
運行結果以下:
code
所有代碼:orm
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Charlie.ConsoleWindow { class Program { static void Main(string[] args) { //測試兩個class相加 Test test1 = new Test(1); Test test2 = new Test(2); Console.WriteLine("兩個class相加的結果爲:"+(test1 +test2).Format()); Console.WriteLine("兩個class比較值大的結果爲:" + (test1 |test2).Format()); } } public class Test { public int ID; public string Name; public Test() { } public Test(int id) { this.ID = id; } public Test(int id, string name) { this.ID = id; this.Name = name; } public static Test operator +(Test t1, Test t2) { if (t2.Name!= null) { return new Test(t1.ID + t2.ID, t1.Name + t2.Name); } else { return new Test(t1.ID + t2.ID); } } public static Test operator |(Test t1, Test t2) { //顯示ID大的class return new Test(t1.ID > t2.ID ? t1.ID:t2.ID); } } internal static class Util { public static string Format(this Test t) { StringBuilder sb = new StringBuilder(); if (t.ID != null) { sb.AppendLine("ID:"+t.ID.ToString()); } if (!string.IsNullOrEmpty(t.Name)) { sb.AppendLine("Name:" + t.Name.ToString()); } return sb.ToString(); } } }
若有錯誤,請你們指正~~~~blog