C#隐式类型局部变量&隐式类型数组

隐式类型局部变量

  可以赋予局部变量推断“类型”var 而不是显式类型。var 关键字指示编译器根据初始化语句右侧的表达式推断变量的类型。推断类型可以是内置类型、匿名类型、用户定义类型或 .NET Framework 类库中定义的类型。  

C#隐式类型局部变量&隐式类型数组
// 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>();
View Code

隐式类型数组

  可以创建隐式类型的数组,在这样的数组中,数组实例的类型是从数组初始值设定项中指定的元素推断而来的。

C#隐式类型局部变量&隐式类型数组
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

  可以和隐匿类型一起使用。

C#隐式类型局部变量&隐式类型数组
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

你可能感兴趣的:(局部变量)