我已经阅读了大量关于c# v4附带的新关键字的文章,但我无法区分“dynamic”和“var”之间的区别。
这篇文章让我思考了一下,但我还是看不出有什么不同。
你是否只能将“var”用作局部变量,但同时用作局部变量和全局变量?
你能显示一些代码没有动态关键字,然后显示相同的代码与动态关键字吗?
我已经阅读了大量关于c# v4附带的新关键字的文章,但我无法区分“dynamic”和“var”之间的区别。
这篇文章让我思考了一下,但我还是看不出有什么不同。
你是否只能将“var”用作局部变量,但同时用作局部变量和全局变量?
你能显示一些代码没有动态关键字,然后显示相同的代码与动态关键字吗?
当前回答
区别就在这里
var is statically typed (compile time), dynamic is dynamically typed (run time) A variable declared as var can only be used locally , dynamic variables can be passed in as params to function (function signature can define a param as dynamic but not var). with dynamic the resolution of the properties happens at runtime and thats not the case with var which means at compile time any variable declared as dynamic can call a method which may or maynot exist and so the compiler would not throw an error. Type casting with var not possible but with dynamic its possible (you can cast an object as dynamic but not as var).
阿伦Vijayraghavan
其他回答
这是一个很好的youtube视频,讨论了var VS动态与实际演示。
下面是一个更详细的快照解释。
Var是早期绑定(静态检查),而dynamic是后期绑定(动态计算)。
Var关键字查看右边的数据,然后在编译时决定左边的数据类型。换句话说,var关键字节省了你输入很多东西。看看下面的图像,当我们给出字符串数据和x变量显示字符串数据类型在我的工具提示。
另一方面,动态关键字的目的完全不同。动态对象在运行时计算。例如,在下面的代码中,“长度”属性是否存在将在运行时计算。我故意输入了一个小的“l”,所以这个程序编译良好,但当它实际执行时,当“length”属性被调用时抛出了一个错误(small“l”)。
用var声明的变量是隐式的,但是是静态类型的。使用dynamic声明的变量是动态类型的。CLR添加此功能是为了支持Ruby和Python等动态语言。
我应该补充一点,这意味着动态声明在运行时解析,var声明在编译时解析。
Var和dynamic定义类型。 Var在编译时,而dynamic在运行时。 在var声明和初始化中,两者都是强制性的,就像常量变量while一样 在动态初始化可以在运行时像只读变量。 在var类型中,无论什么类型都是在初始化时确定的,但不能更改下一步 动态可以采用任何类型,甚至用户定义的数据类型。
Var(隐式类型局部变量)关键字用于定义局部变量。对于Var,底层数据类型是在编译时根据初始赋值确定的。一旦使用Var类型进行了初始赋值,那么它将成为强类型。如果您试图存储与Var类型不兼容的值,则会导致编译时错误。
例子:
Var strNameList=new List<string>(); By using this statement we can store list of names in the string format.
strNameList.add("Senthil");
strNameList.add("Vignesh");
strNameList.add(45); // This statement will cause the compile time error.
但在动态类型中,底层类型仅在运行时确定。在编译时不检查动态数据类型,也不是强类型。我们可以为动态类型分配任何初始值,然后可以在其生命周期内将其重新分配给任何新值。
例子:
dynamic test="Senthil";
Console.Writeline(test.GetType()) // System.String
test=1222;
Console.Writeline(test.GetType()) // System.Int32
test=new List<string>();
Console.Writeline(test.GetType()) //System.Collections.Generic.List'1[System.String]
它也不提供智能感知支持。当我们使用linq工作时,它也没有提供更好的支持。因为它不支持lambda表达式、扩展方法和匿名方法。
下面是一个简单的例子,演示了动态(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