[英]Type inference in C#
I know msdn should probably be the first place to go and it will be after I get the scoop here. 我知道msdn应该是第一个去的地方,它将在我得到这里的独家新闻之后。 What the msdn would not really provide as part of the technical specification is what I am about to ask now:
作为技术规范的一部分,msdn不会真正提供的是我现在要问的问题:
To bring a note of specifics to the question, it would be really interesting to know (in pseudo code) of how the compiler can actually determine the needed type if the method was called using lambdas and type inference
为了记录这个问题的细节,如果使用lambdas和类型推断调用该方法,那么知道(在伪代码中)编译器如何实际确定所需类型将是非常有趣的。
I am looking to see the compiler logical flow on how to locate that type. 我期待看到关于如何定位该类型的编译器逻辑流程。
Type inference occurs in many places in C#, at least the following: 类型推断发生在C#的许多地方,至少如下:
var
keyword, which tells the compiler to infer (deduce) the correct type for the variable from what you initialize it with var
关键字,它告诉编译器根据初始化变量来推断(推导)变量的正确类型 And to answer your questions: 并回答你的问题:
1) It saves a lot of typing, especially when using the so-called "LINQ methods". 1)它节省了大量的输入,特别是在使用所谓的“LINQ方法”时。 Compare for example
比较例如
List<string> myList = new List<string>();
// ...
IEnumerable<string> result = myList.Where<string>((string s) => s.Length > 0)
.Select<string, string>((string s) => s.ToLower());
versus 与
var myList = new List<string>();
// ...
var result = myList.Where(s => s.Length > 0).Select(s => s.ToLower());
2) I don't know what you mean by "correlation", but without the var
keyword you couldn't have variables refer to anonymous types in a type-safe way (you could always use object
or dynamic
), which makes it pretty important when using anonymous types. 2)我不知道“关联”是什么意思,但如果没有
var
关键字,你就不能以类型安全的方式引用匿名类型(你总是可以使用object
或dynamic
),这使得它很漂亮使用匿名类型时很重要。
3) Nothing as far as I can think of. 3)我无法想到的任何事情。 It's only a convenience feature.
这只是一个方便的功能。 Of course its absence would make, for instance, the aforementioned anonymous types less useful, but they're mostly a convenience feature as well.
当然,它的缺席会使上述匿名类型不那么有用,但它们大多也是一个便利功能。
4) I think 3) answers this as well. 4)我认为3)也回答这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.