dynamic和System.Object之间的区别

时间:2010-08-12 01:22:32

标签: c# .net 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());
}

4 个答案:

答案 0 :(得分:10)

区别在于MyTestVar2.ToUpper()编译和工作,没有任何明确的转换。

object是普通类型 dynamic基本上是一个占位符类型,它使编译器发出动态的后期绑定调用。

GetType()是由object类定义的正常函数,它在您调用它的实例上运行。
GetType()完全不受引用的变量的声明类型的影响,该变量引用您调用它的对象。 (除了无效之外)

答案 1 :(得分:3)

你应该从这个出色的MSDN article开始。差异可以简明扼要地总结出来:

  

在编译时,是一个元素   键入为动态假定支持   任何操作。

System.Object只支持少数几项操作 - ToString()Equals()等。

答案 2 :(得分:3)

根本区别在于编译时(对象)与运行时(对于动态)重新调用呼叫。它也被称为早期与晚期绑定。 [注意:添加对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 

如果你注释掉最后一个调用,应用程序应该运行正常,因为CLR在运行时到达第二个最后一次调用d.ToUpper()时,它将在字符串类型中查找方法ToUpper()并将在那里找到它(因为在第二个语句中d被分配了一个字符串)。最后一次调用没有编译,因为在编译时正在System.Object类型中搜索ToUpper(),当然不会在那里。

答案 3 :(得分:0)

对象和动态之间的唯一区别。

对于对象,要从对象中检索值时,需要显式类型转换。

如果喜欢的话请给个赞。

相关问题