什么时候有效使用匿名类型? [英] When is efficient to use anonymous types?

查看:88
本文介绍了什么时候有效使用匿名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是var关键字。例如

  var  a =  10 ; 

  int  a =  10 ; 

。在我看来,程序是值得的,因为在使用var关键字的情况下,编译器应该为给定变量选择正确的类型。

解决方案

< blockquote> 这不是匿名类型;这只是从类型推断获得的类型。考虑

  var  stringBuilder =  new 系统.Text.StringBuilder(); 
string whatIsIt = stringBuilder.GetType()。FullName;

最后一行将返回System.Text.StringBuilder,相当完全命名:-);并且第一行是严格等同

 System.Text.StringBuilder(); stringBuilder =  new  System.Text.StringBuilder(); 





所以,这只是语法,语法糖 http://en.wikipedia.org/wiki/Syntactic_sugar [ ^ ])。



您可以尝试使用相同的数字和字符串,将看到具体的命名类型。



我猜你的表现很明显可以使用这个功能:当你知道编译器的猜测是显而易见的并且你得到了你所期望的。



匿名类型是完全不同的:https://msdn.microsoft.com/en-us/library/bb397696.aspx [ ^ ]。



-SA


I mean "var" keyword.For example

var a=10;

or

int a=10;

.In my opinion program will work worth,becouse in situation of using var keyword,compiler should choose right type for given variable.

解决方案

This is not an anonymous type; this is just a type obtained from type inference. Consider

var stringBuilder = new System.Text.StringBuilder();
string whatIsIt = stringBuilder.GetType().FullName;

The last line will return "System.Text.StringBuilder", quite fully named :-); and the first line is strictly equivalent to

System.Text.StringBuilder(); stringBuilder = new System.Text.StringBuilder();



So, this is nothing but syntax, syntactic sugar (http://en.wikipedia.org/wiki/Syntactic_sugar[^]).

You can try the same with the number and the string, will see a concrete named type.

I guess it's apparent when you can use this feature: when you know that "compiler's guess" is apparent and you get what you expected.

And anonymous type is something totally different: https://msdn.microsoft.com/en-us/library/bb397696.aspx[^].

—SA


这篇关于什么时候有效使用匿名类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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