C#中“var”和“object”的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1552881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between "var" and "object" in C#
提问by user184805
Is the var
type an equivalent to Variant
in VB? When object
can accept any datatype, what is the difference between those two?
该var
类型是否等同Variant
于 VB 中的类型?什么时候object
可以接受任何数据类型,这两者有什么区别?
采纳答案by Tarik
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var
. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i
are functionally equivalent:
从 Visual C# 3.0 开始,在方法范围内声明的变量可以具有隐式类型var
。隐式类型的局部变量是强类型的,就像您自己声明了类型一样,但编译器会确定类型。以下两个声明i
在功能上是等效的:
var i = 10; //implicitly typed
int i = 10; //explicitly typed
var isn't object
var 不是对象
You should definitely read this : C# 3.0 - Var Isn't Object
您绝对应该阅读以下内容:C# 3.0 - Var 不是对象
回答by user184805
Nope - var
just means you're letting the compiler infer the type from the expression used to assign a value to the variable.
不 -var
只是意味着您让编译器从用于为变量赋值的表达式推断类型。
It's just syntax sugar to let you do less typing - try making a method parameter of type "var
" and see what happens :]
这只是语法糖,让您少打字 - 尝试制作类型为“ var
”的方法参数,看看会发生什么:]
So if you have an expression like:
所以如果你有这样的表达式:
var x = new Widget();
x
will be of type Widget
, not object
.
x
将是 类型Widget
,不是object
。
回答by Mike Valenty
The other answers are right on, I'd just like to add that you can actually put your cursor on the 'var' keyword and hit F12 to jump to the inferred type declaration.
其他答案是正确的,我只想补充一点,您实际上可以将光标放在“var”关键字上,然后按 F12 跳转到推断的类型声明。
回答by Devendra Patel
For more details have a look at http://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp
有关更多详细信息,请查看 http://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp
回答by Anand Ramachandran
Adding to the post.
添加到帖子中。
Parent p = new Parent();
Child c = new Child();//Child class derives Parent class
Parent p1 = new Child();
With above you can only access parent (p1) properties eventhough it holds child object reference.
上面你只能访问父(p1)属性,即使它持有子对象引用。
var p= new Parent();
var c= new Child();
var p1 = new Child();
when using 'var' instead of class, you have access to both the parent and child class properties. it behaves like creating object for child class.
当使用 'var' 而不是 class 时,您可以访问父类和子类属性。它的行为就像为子类创建对象。
回答by Masoud
one difference is Boxing and Unboxing with Object.
一个区别是用对象装箱和拆箱。