我已经阅读了大量关于c# v4附带的新关键字的文章,但我无法区分“dynamic”和“var”之间的区别。

这篇文章让我思考了一下,但我还是看不出有什么不同。

你是否只能将“var”用作局部变量,但同时用作局部变量和全局变量?

你能显示一些代码没有动态关键字,然后显示相同的代码与动态关键字吗?


当前回答

Var只是普通类型声明的简写,让编译器猜测正确的类型。

Dynamic是一种新的(静态)类型,其中所有检查都在运行时完成,而不是由编译器完成。

其他回答

下面是一个简单的例子,演示了动态(4.0)和Var之间的差异

dynamic  di = 20;
dynamic ds = "sadlfk";
var vi = 10;
var vsTemp= "sdklf";

Console.WriteLine(di.GetType().ToString());          //Prints System.Int32
Console.WriteLine(ds.GetType().ToString());          //Prints System.String
Console.WriteLine(vi.GetType().ToString());          //Prints System.Int32
Console.WriteLine(vsTemp.GetType().ToString());      //Prints System.String

**ds = 12;**   //ds is treated as string until this stmt now assigning integer.

Console.WriteLine(ds.GetType().ToString());          **//Prints System.Int32**

**vs = 12**; //*Gives compile time error* - Here is the difference between Var and Dynamic. var is compile time bound variable.

湿婆Mamidi

用var声明的变量的类型是由编译器决定的,它是指定类型名称的快捷方式,仅此而已。

然而动态是在运行时确定的,编译器不知道实际的类型,所有对该变量的方法/字段/属性访问都将在运行时计算出来。

Do not confuse dynamic and var. Declaring a local variable using var is just a syntactical shortcut that has the compiler infer the specific data type from an expression. The var keyword can be used only for declaring local variables inside a method while the dynamic keyword can be used for local variables, fields, and arguments. You cannot cast an expression to var, but you can cast an expression to dynamic. You must explicitly initialize a variable declared using var while you do not have to initialize a variable declared with dynamic.

Var只是普通类型声明的简写,让编译器猜测正确的类型。

Dynamic是一种新的(静态)类型,其中所有检查都在运行时完成,而不是由编译器完成。

动态变量和var变量都可以存储任何类型的值,但需要在声明时初始化'var'。

编译器没有关于变量的“动态”类型的任何信息。 Var是编译器安全的,即编译器拥有关于存储值的所有信息,因此它不会在运行时引起任何问题。

动态类型可以作为函数参数传递,函数也可以返回它。 Var类型不能作为函数参数传递,函数不能返回对象类型。这种类型的变量可以在其定义的范围内工作。

在动态类型转换的情况下,不需要,但你需要知道与存储类型相关的属性和方法,而对于var不需要类型转换,因为编译器有执行操作的所有信息。

dynamic:在使用反射或动态语言支持或COM对象编码时很有用,因为我们需要编写更少的代码。

var:在从linq查询中获取结果时有用。在3.5框架中引入了对linq特性的支持。

参考:咨询byabhi