问题描述
声明为动态的变量,并声明为System.Object的一个变量之间的区别是什么?运行下面的函数似乎表明,这两个变量会马上转换为正确的类型动态:
无效ObjectTest()
{
System.Object的MyTestVar =测试;
动态MyTestVar2 =测试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()
编译和工作,无任何显式类型转换。
对象
是一个普通型。动态
是一个基本上是一个占位符类型,导致编译器发出的动态后期绑定调用。
的GetType()
是由对象
类,经营上的实例中定义的普通函数的,你就调用它。的GetType()
是指向你调用它的对象变量的声明的类型完全不受影响。 (除nullables)
What is the difference between a variable declared as dynamic and a variable declared as System.Object? Running the following function would seem to indicate that both variables get cast to the correct type dynamically:
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());
}
The difference is that MyTestVar2.ToUpper()
compiles and works, without any explicit casting.
object
is a normal type.dynamic
is a basically a placeholder type that causes the compiler to emit dynamic late-bound calls.
GetType()
is a normal function defined by the object
class that operates on the instance that you call it on.GetType()
is completely unaffected by the declared type of a variable that refers to the object you call it on. (except for nullables)
这篇关于充满活力和System.Object的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!