更新时间:2022-10-23 19:44:37
没有的东西,他们是非常不同的。
VAR
表示在编译时推断变量的类型。 - 但它仍然是完全静态绑定
动态
表示假设我可以做任何事情,我想和这个变量。 - 即编译器不知道哪些操作是可用的,而DLR将制定出什么样的呼吁的真正的意思是在执行时间。
我指望用动态
很少 - 只有当我真正想要的动态行为:
VAR
让你赶上在编译时错别字等When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)
Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?
var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
No, they're very different.
var
means "infer the type of the variable at compile-time" - but it's still entirely statically bound.
dynamic
means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls really mean at execution time.
I expect to use dynamic
very rarely - only when I truly want dynamic behaviour:
var
lets you catch typos etc at compile-time