69
A
回答
128
这意味着宣布本地存在的类型将由编译器推断:
// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";
值得注意的是,var
没有定义的变量为动态类型。因此,这是不合法的:
var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints
var
只有两个用途:
- 它需要较少的打字声明变量,变量声明为嵌套泛型类型时尤其如此。
- 必须存储到一个匿名类型的对象的引用时使用,因为类型名称不能提前知道:
var foo = new { Bar = "bar" };
不能使用var
作为任何东西,但当地人的类型。因此,您不能使用关键字var
来声明字段/属性/参数/返回类型。
12
这意味着数据类型是从上下文派生(暗示)的。
http://msdn.microsoft.com/en-us/library/bb383973.aspx从
在于在方法范围中声明可以 具有隐式类型变种的Visual C#3.0,变量 开始。一个 隐式类型局部变量是 强类型,就好像您自己已经声明了 类型,但 编译器确定类型。 i的 以下两个声明是 功能上等同的:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
var
是用于消除键盘打字和视觉噪声,例如有用,
MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();
变得
var x = new MyReallyReallyLongClassName();
但可以被滥用到可读性被牺牲的地步。
7
“var”表示编译器将根据使用情况确定变量的显式类型。例如,
var myVar = new Connection();
会给你一个Connection类型的变量。
3
你有没有讨厌写这样的变量初始值设定项?
XmlSerializer xmlSerializer = new XmlSerialzer(typeof(int))
所以,从C#3.0,你可以用
var xmlSerializer = new XmlSerialzer(typeof(int))
一个通知更换:编译时类型得到解决,所以其性能没有问题。但编译器应该能够在构建步骤中检测类型,所以像var xmlSerializer;
这样的代码根本不会编译。
4
它根据在初始化中分配给它的内容来声明一个类型。
一个简单的例子是,代码:
var i = 53;
将审查53的类型,基本上是重写此为:
int i = 53;
请注意,虽然我们可以有:
long i = 53;
这不会发生在var。尽管它可以用:
var i = 53l; // i is now a long
同理:
var i = null; // not allowed as type can't be inferred.
var j = (string) null; // allowed as the expression (string) null has both type and value.
这可能是一个小的便利与复杂类型。它与匿名类型更为重要:
var i = from x in SomeSource where x.Name.Length > 3 select new {x.ID, x.Name};
foreach(var j in i)
Console.WriteLine(j.ID.ToString() + ":" + j.Name);
在这里有定义i
和j
比使用var
,因为是他们持有的类型没有名字,没有其他办法。
相关问题
- 1. @var在php中的含义是什么
- 2. “System.IO”在C#中的含义是什么?
- 3. PLAT_BINARYFORMATTER在C#中的含义是什么?
- 4. var,_ =在Python中的含义是什么?字符串连接?
- 5. C中“wild pointer”的含义是什么?
- 6. C#中“@”的含义是什么
- 7. C++中[=](...){...}的含义是什么?
- 8. :: C++中的含义是什么?
- 9. C#中'this'的含义是什么?
- 10. C#中“=>”的含义是什么?
- 11. C++宏中“##”的含义是什么?
- 12. C++中NULL!= value的含义是什么?
- 13. C中'=='的含义是什么?
- 14. =的含义是什么?在目标c
- 15. /var/log/messages中错误编号的含义是什么?
- 16. 线的含义是什么:var DYN_WEB = DYN_WEB || {};在js?
- 17. 这是' - >'在c/objective-c中的含义是什么?
- 18. 什么(char)0在C++中的含义?
- 19. 这个类定义在C#中的含义是什么?
- 20. {$ C PRELOAD}指令的含义是什么?
- 21. C(字符串)在C++中的含义是什么?
- 22. 在$ {var?}中,bash变量参数展开中问号的含义是什么?
- 23. 什么VAR = VAR &&“*”的意思是在Javascript
- 24. BackoffMultiplier在DefaultRetryPolicy中的含义是什么?
- 25. arg在WordPress中的含义是什么
- 26. {}在perl中的含义是什么?
- 27. _._在包装中的含义是什么?
- 28. 'AS'在SQL中的含义是什么?
- 29. “**”在ANT中的含义是什么?
- 30. $ parent在AngularJS中的含义是什么?
这是一个很好的例子,说明Stack Exchange上需要的答案。有时候人们会忽略重要的信息和/或不够简短。 – Panzercrisis 2016-04-12 14:03:37