English 中文(简体)
这种推论有什么好处?
原标题:What is the advantage of this type inference?
  • 时间:2011-11-11 13:54:14
  •  标签:
  • c#

我们可以采用这种推论:

var myList = new List<int>();

但它没有真正帮助吗? 由于这仍然要求我们只增加一点点,因此,仅仅宣布暗中变数而不是变数会更容易吗?

最佳回答

www.un.org/Depts/DGACM/index_french.htm 并没有改变汇编者的产出,只是缩短了编码。

唯一时间是<代码>var提供匿名类型:

var foo = new { Bar = 123 };

必须理解<代码>var。 页: 1 (从允许物体类型发生变化的意义上来说),这只是允许你宣布一个变数,使汇编者照你宣布的类型。

问题回答
IEnumerable<MadeUpEmbarrassinglyLongClassName> stupidVariable = new IEnumerable<MadeUpEmbarrassinglyLongClassName>();

v

var stupidVariable = new IEnumerable<MadeUpEmbarrassinglyLongClassName>();

阅读容易些什么?

更简明扼要的是:

List<int> myList = new List<int>();

我猜测,这或许会更容易阅读,尽管在这个三维案例中,情况并非如此。

此外,如果可以明智地标明变量,那么该变量的类型应当相当明确。

<代码>var在分配价值之前为未知类型。 一旦分配价值,就成为分配的类型。 当你在汇编时间时可以推断其将具有何种价值时,则使用/code>。 <代码>var的另一种情况是准则Q的查询。 不是设立特殊类别来处理你的询问,而是简单地将结果分配到<条码>/条码>,其余部分。 您肯定会赞同<条码>瓦尔<>。 页: 1

In your example, there is no advantage. In fact, I believe that code readability suffers a bit (opinion).

The answer to this quesiton boils down to personal preference. The compiler will infer List<int>() if var is used. Which would you prefer to look at? Which would your peers prefer to look at?





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签