C#中的类型推断 [英] Type inference in C#

查看:51
本文介绍了C#中的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道msdn应该是第一个应该去的地方,它将是在我得到独家新闻之后.我现在要问的是,msdn不会真正提供作为技术规范一部分的内容:

I know msdn should probably be the first place to go and it will be after I get the scoop here. What the msdn would not really provide as part of the technical specification is what I am about to ask now:

  1. 该主题在日常开发过程中到底有多有用?
  2. 它与clr内的匿名类型是否具有任何形状或形式的关联?
  3. 如果没有它,本来可以做些什么呢?
  4. .net的哪些功能取决于主题,并且没有作为框架的一部分就不可能存在吗?

为了使问题更具体,如果使用lambdas和类型推断调用该方法,(以伪代码)知道编译器如何实际确定所需的类型将是非常有趣的事情

我希望看到有关如何找到该类型的编译器逻辑流程.

I am looking to see the compiler logical flow on how to locate that type.

推荐答案

在C#中的许多地方都会发生类型推断,至少是以下情况:

Type inference occurs in many places in C#, at least the following:

  1. var 关键字,它告诉编译器从您使用变量初始化的内容中推断(推断)出正确的变量类型
  2. 将类型参数保留在泛型方法调用之外的能力,只要可以从参数中推断出它们即可
  3. 只要可以推论,就可以从lambda表达式参数中排除类型
  1. The var keyword, which tells the compiler to infer (deduce) the correct type for the variable from what you initialize it with
  2. The ability to leave type parameters out of a generic method call as long as they can be deduced from the parameters
  3. The ability to leave out types from lambda expression arguments, as long as they can be deduced

并回答您的问题:

1)它节省了很多键入操作,尤其是在使用所谓的"LINQ方法"时.比较例如

1) It saves a lot of typing, especially when using the so-called "LINQ methods". 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());

var myList = new List<string>();
// ...
var result = myList.Where(s => s.Length > 0).Select(s => s.ToLower());

2)我不知道您所说的相关性"是什么意思,但是如果没有 var 关键字,您将无法使用类型安全的方式来引用匿名类型的变量(您可以始终使用 object dynamic ),这在使用匿名类型时非常重要.

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.

3)我想不到的.这只是一项便利功能.当然,如果没有它,例如,上述匿名类型将不再有用,但它们基本上也是一种便利功能.

3) Nothing as far as I can think of. 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)我想3)也回答了这个问题.

4) I think 3) answers this as well.

这篇关于C#中的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆