thr*_*thr 18 .net c# type-inference
C#类型推断有多好?我在某处读到它只适用于局部变量?它是否适用于类级属性?对于方法签名?方法返回类型?等等
Jon*_*eet 41
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
Run Code Online (Sandbox Code Playgroud)
编辑:Tye推理的另一个例子是Lambdas.IE:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8102 次 |
| 最近记录: |