Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态对象和系统对象之间的区别_C#_.net_Variables_Dynamic_.net 4.0 - Fatal编程技术网

C# 动态对象和系统对象之间的区别

C# 动态对象和系统对象之间的区别,c#,.net,variables,dynamic,.net-4.0,C#,.net,Variables,Dynamic,.net 4.0,声明为动态的变量和声明为System.Object的变量之间有什么区别?运行以下函数似乎表明这两个变量动态转换为正确的类型: void ObjectTest() { System.Object MyTestVar = "test"; dynamic MyTestVar2 = "Testing 123"; Console.WriteLine("{0}", MyTestVar.GetType()); Console.WriteLine("{0}", MyTestVa

声明为动态的变量和声明为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());
}

不同之处在于
MyTestVar2.ToUpper()
编译并工作,无需任何显式强制转换

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

GetType()
是一个由
对象定义的普通函数,该对象对调用它的实例进行操作。

GetType()
完全不受引用调用它的对象的变量的声明类型的影响。(可为空的除外)

您可能应该从这个优秀的选项开始。这些差异可以非常简洁地概括为:

在编译时,一个元素 假设类型化为动态以支持 任何行动


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

基本区别在于编译时(对于对象)与运行时(对于动态)调用的资源解析。它也被称为早期绑定和后期绑定。[注意:添加对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(),当然不会在那里

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

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


如果您觉得合适,请给出一个like。

您可以调用
动态变量的任何方法。代码<代码>动态x=3;x、 爆炸()
将完美编译我不久前写了一篇文章: