【发布时间】:2010-10-03 13:16:51
【问题描述】:
C# 类型推断有多好?我在某处读到它仅适用于局部变量?它适用于类级别属性吗?对于方法签名?方法返回类型?等等
【问题讨论】:
标签: c# .net type-inference
C# 类型推断有多好?我在某处读到它仅适用于局部变量?它适用于类级别属性吗?对于方法签名?方法返回类型?等等
【问题讨论】:
标签: c# .net type-inference
C# 中有几种主要的类型推断:
隐式类型的局部变量:
泛型方法类型参数推断,即您没有在调用泛型方法时指定类型参数,编译器会根据参数计算出来。
Lambda 表达式参数类型推断
数组类型推断,例如new[] { "Hi", "there" } 而不是 new string[] { "Hi", "there" }
我可能忘记了一些其他可能被称为“类型推断”的功能。我怀疑您最感兴趣的是第一个,但其他可能也与您相关:)
【讨论】:
它只能用于局部变量,但它可以检测多种不同形式的类型。
var myVar = SomeMethodThatReturnsInt(); //will know it's an int
var myIntList = new List<int>(); //this works too (although this is technically not type inference)
var myOwnVar = new { Name = "John", Age = 100 }; // will create own type and infer that
编辑:Tye 推理的另一个例子是 Lambdas。即:
var myList = new List<int>();
//add some values to list
int x = myList.Find(i => i == 5); // compiler can infer that i is an int.
【讨论】:
据我所知,它仅适用于局部变量。
【讨论】: