C#隱式類型局部變數&隱式類型數組

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.