Ice*_*ind 13 .net c# variables dynamic .net-4.0
声明为dynamic的变量和声明为System.Object的变量之间有什么区别?运行以下函数似乎表明两个变量都动态地转换为正确的类型:
void ObjectTest()
{
System.Object MyTestVar = "test";
dynamic MyTestVar2 = "Testing 123";
Console.WriteLine("{0}", MyTestVar.GetType());
Console.WriteLine("{0}", MyTestVar2.GetType());
MyTestVar = 123;
MyTestVar2 = 321;
Console.WriteLine("{0}", MyTestVar.GetType());
Console.WriteLine("{0}", MyTestVar2.GetType());
}
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 10
不同之处在于MyTestVar2.ToUpper()编译和工作,没有任何明确的转换.
object是正常类型.
dynamic基本上是一个占位符类型,它使编译器发出动态的后期绑定调用.
GetType()是一个正常的函数,由在您调用它object的实例上运行的类定义.
GetType()完全不受声明的变量类型的影响,该变量引用您调用它的对象.(除了nullables)
根本区别在于 编译时(对于对象)与运行时(对于动态)调用的解析。它也称为早期与晚期绑定。[注意:添加对 Microsoft.CSharp 的引用,以便编译以下代码。]
object o = "Hello world";// fine because a derived type can be assigned to a base type
dynamic d= "Hello world";// fine as well
Type otype=o.GetType();// compiles because it confirms that object has a GetType()
Type dtype=d.GetType();// also compiles but for another reason (i.e.no binding yet)
string upperd= d.ToUpper(); // compiles because no binding yet ( anything goes :)
string uppero= o.ToUpper(); // Fails to compile. Object has no ToUpper() method
Run Code Online (Sandbox Code Playgroud)
如果您注释掉最后一次调用,应用程序应该可以正常运行,因为 CLR 在运行时到达第二个最后一次调用 d.ToUpper() 时,它将在字符串类型中查找方法 ToUpper() 并在那里找到它(因为在第二个语句中 d 被分配了一个字符串)。最后一次调用没有编译,因为 ToUpper() 在编译时正在 System.Object 类型中搜索,当然不会在那里。