吃午飯前繼上篇泛型再寫一篇關(guān)于泛型的文章,雖然總是被博客園移出首頁(yè),文章不精確實(shí)是大問(wèn)題啊,會(huì)再接再厲的。進(jìn)入正題。
先來(lái)說(shuō)下泛型約束。當(dāng)我們?cè)谑褂梅盒偷臅r(shí)候通常會(huì)希望使用泛型實(shí)參時(shí),參數(shù)能具備某一些特性,這時(shí)"泛型約束"來(lái)了,它能幫助我們?cè)趥魅敕盒蛥?shù),該參數(shù)要實(shí)現(xiàn)先前指定的約束。有4種約束可用,如下:
1 public struct DoDo<T> where T : class2 {}3 public class BiBi<T> where T : struct4 {}5 public struct CoCo<T> where T : new()6 {}7 public struct DkDk<T> where T : System.Data.IDbConnection8 {}上述四個(gè)分別對(duì)應(yīng)四種類型約束(僅僅在單個(gè)使用),下面來(lái)說(shuō)下在組合使用的情況。
組合使用有兩點(diǎn)要注意:
1 //不能同時(shí)指定類型參數(shù)既是引用類型又是值類型 2 //public struct DoDo<T> where T : class, struct 3 //{} 4 5 public class BiBi<T> where T : Stream, new() 6 {} 7 8 //使用構(gòu)造類型約束,new()要放在最后 9 //public class LiLi<T> where T : new(), Stream10 //{}11 12 public struct CoCo<T> where T : class, IDisposable , new()13 {}14 15 //如下一個(gè)約束是類,要放在接口的前面16 //public struct FeFe<T> where T : IDisposable, class, new()17 //{}使用泛型約束知識(shí)都在上面了,更多的去理解和消化。在使用泛型方法時(shí),讓編譯器是推斷能讓我們的代碼更簡(jiǎn)短,但可讀性可能不高。
------------------------------------------------------------------------------------------------------------------------------------------
Point 1 關(guān)于靜態(tài)字段和靜態(tài)構(gòu)造方法,每一個(gè)封閉類型有一個(gè)靜態(tài)字段,如果有的話
1 StaticConstraint<int> intStatic = new StaticConstraint<int>();2 StaticConstraint<int>.StaticValue = "int";3 4 StaticConstraint<double> doubleStatic = new StaticConstraint<double>();5 StaticConstraint<double>.StaticValue = "double";6 7 StaticConstraint<char> charStatic = new StaticConstraint<char>();8 StaticConstraint<char>.StaticValue = "char";
Point 2 使用typeof獲取類型
typeof可通過(guò)兩種方式作用于泛型類型,一種用來(lái)獲取未綁定泛型類型,一種用來(lái)獲取特定的已構(gòu)造類型。前一種需要提供泛型的名稱,去除所有類型參數(shù)的名稱,但要保留逗號(hào),后一種需要采取與聲明泛型類型變量相同的方式指定類型參數(shù)即可。
1 static void GetTypeOfConstraint<X>() 2 { 3 //獲取未綁定泛型類型 4 Console.WriteLine(typeof(X)); 5 Console.WriteLine(typeof(List<>)); 6 Console.WriteLine(typeof(Dictionary<,>)); 7 8 //獲取已構(gòu)造類型 9 Console.WriteLine(typeof(List<int>));10 Console.WriteLine(typeof(Dictionary<int, double>));11 }請(qǐng)斧正。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注