var (C# مرجع)

Beginning في Visual C# 3.0, متغيرات that are declared at أسلوب نطاق can have an implicit نوع var. An الكتابة الضمنية للمتغير المحلي هو strongly typed just كـ if you had declared the نوع yourself, but the compiler determines the نوع. The following الثاني تصريحات of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

للمزيد من المعلومات، راجع المتغيرات المحلية ذات النوع المُختار ضمنياً (دليل البرمجة لـ #C) وعلاقات النوع في عمليات الاستعلام LINQ (C#).

مثال

The following مثال shows الثاني استعلام expressions. في التعبير أول، استخدم varهو المسموح بها ولكن هو غير مطلوب، لأن نوع نتيجة الاستعلام يمكن أن يرد بوضوح IEnumerable<string>. ومع ذلك، في التعبير الثاني، varيجب أن يستخدم لأن النتيجة هو مجموعة من أنواع المستخدمين المجهولين، واسم ذلك النوع هو لا يمكن الوصول إليه إلا للمترجم نفسه. لاحظ أنه في مثال رقم 2، foreachمتغير تكرار itemيجب أيضا ضمنياً كتابة.

// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}

راجع أيضًا:

المرجع

المتغيرات المحلية ذات النوع المُختار ضمنياً (دليل البرمجة لـ #C)

المبادئ

دليل البرمجة لـ #C

موارد أخرى

مرجع C#‎