可以給予區域變數推斷「型別」var,而非明確型別

 var 關鍵字會指示編譯器從初始化陳述式右側的運算式推斷變數的型別。 

推斷的型別可能是內建型別、匿名型別、使用者定義型別。

// i is compiled as an int
var i = 5;

// s is compiled as a string
var 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 type
var anon = new { Name = "Terry", Age = 34 };

// list is compiled as List<int>                             
var list = new List<int>();

在 for 初始化陳述式中。

for(var x = 1; x < 10; x++)

在 foreach 初始化陳述式中。
foreach(var item in list){...}
在 using 陳述式中。

using (var file = new StreamReader("C:\\myfile.txt")) {...}
class ImplicitlyTypedLocals2
{
    static void Main()
    {
        string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };

        // If a query produces a sequence of anonymous types, 
        // then use var in the foreach statement to access the properties.
        var upperLowerWords =
             from w in words
             select new { Upper = w.ToUpper(), Lower = w.ToLower() };

        // Execute the query
        foreach (var ul in upperLowerWords)
        {
            Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
        }
    }
}

資料來源:http://msdn.microsoft.com/zh-tw/library/bb384061.aspx

arrow
arrow
    全站熱搜

    東勢厝滴yang 發表在 痞客邦 留言(0) 人氣()