標籤:style blog http color 使用 strong
【隱式類型局部變數】
可以賦予局部變數推斷“類型”var 而不是顯式類型。var 關鍵字指示編譯器根據初始化語句右側的運算式推斷變數的類型。推斷類型可以是內建類型、匿名型別、使用者定義型別或 .NET Framework 類庫中定義的類型。
// i is compiled as an intvar i = 5;// s is compiled as a stringvar s = "Hello";// a is compiled as int[]var a = new[] { 0, 1, 2 };// expr is compiled as IEnumerable<Customer>// or perhaps IQueryable<Customer>var expr = from c in customers where c.City == "London" select c;// anon is compiled as an anonymous typevar anon = new { Name = "Terry", Age = 34 };// list is compiled as List<int> var list = new List<int>();
View Code
【隱式類型數組】
可以建立隱式類型的數組,在這樣的數組中,數組執行個體的類型是從陣列初始設定式中指定的元素推斷而來的。
class ImplicitlyTypedArraySample{ static void Main() { var a = new[] { 1, 10, 100, 1000 }; // int[] var b = new[] { "hello", null, "world" }; // string[] // single-dimension jagged array var c = new[] { new[]{1,2,3,4}, new[]{5,6,7,8} }; // jagged array of strings var d = new[] { new[]{"Luca", "Mads", "Luke", "Dinesh"}, new[]{"Karen", "Suma", "Frances"} }; }}
View Code
可以和隱匿類型一起使用。
var contacts = new[] { new { Name = " Eugene Zabokritski", PhoneNumbers = new[] { "206-555-0108", "425-555-0001" } }, new { Name = " Hanying Feng", PhoneNumbers = new[] { "650-555-0199" } }};
View Code
參考:
1、http://msdn.microsoft.com/zh-cn/library/bb383973(v=vs.90).aspx
2、http://msdn.microsoft.com/zh-cn/library/bb384061(v=vs.90).aspx
3、http://msdn.microsoft.com/zh-cn/library/bb384090(v=vs.90).aspx