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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:46:02  来源:igfitidea点击:

Difference between "var" and "object" in C#

c#types

提问by user184805

Is the vartype an equivalent to Variantin VB? When objectcan 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 iare 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 - varjust 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();

xwill 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 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.

一个区别是用对象装箱和拆箱。