如何好,是C#的类型推断? [英] How good is the C# type inference?

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

问题描述

如何好,是C#的类型推断?我读的地方,它只是局部变量?不知是否对类级属性的工作?对于方法签名?方法的返回类型?等等。

How good is C# type inference? I read somewhere that it's only for local variables? Does it work for class level attributes? For method signatures? Method return types? etc.

推荐答案

有在C#中的几个主要品种类型推断的:

There are a few main kinds of type inference in C#:

  • 隐式类型的局部变量:

  • Implicitly typed local variables:

  • 仅限于局部变量
  • 只有当价值被指定为声明的一部分
  • 值不能为null
  • 在值不能为一个lambda EX pression,匿名方法或方法组(没有投)
  • 的值的编译时类型用于变量
  • 的类型
  • 变量的任何进一步使用仅核对由最初的声明+赋值确定的类型;它们不向推理本身。

泛型方法的类型参数推断,即你不指定调用一个泛型方法的类型参数,根据参数的编译器计算出来。

Generic method type argument inference, i.e. you don't specify the type arguments in a call to a generic method, the compiler figures them out based on the arguments.

  • 将是非常方便有这个泛型类型以及泛型方法
  • 真的很方便呢 - LINQ将是很难​​或不可能没有它使用
  • 匿名类型是没有它
  • 相当无用
  • 在非常复杂的规则,即使该规范是错在一些地方

LAMBDA EX pression参数类型推断

Lambda expression parameter type inference

  • 在编译器试图制定出基于在它的使用范围内的参数的lambda EX pressions类型
  • 在通常工作pretty的很好,在我的经验

数组类型推断,例如新的[] {你好,有} 而不是新的String [] {你好,有}

Array type inference, e.g. new[] { "Hi", "there" } instead of new string[] { "Hi", "there" }

  • 在各种小的限制,没有重大

我可能已经忘记了其他的一些功能可能被称为类型推断。我怀疑你最感兴趣的是第一个,但其他人可能与您太:)

I've probably forgotten some other features which might be called "type inference". I suspect you're mostly interested in the first, but the others might be relevant to you too :)

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

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