首先反映动态类型以告知它是否是动态类型

有没有一种方法可以判断对象被分配的类型是动态类型?

例如:

dynamic foo = GetCat(); Console.WriteLine( (foo is Cat).ToString() ); // will print True because // at the execution time, foo will have assumed the Cat type. However, is // there a mechanism by which I can reflect on foo and say, "This guy was assigned // a dynamic type, to begin with."? 

有没有办法可以判断对象被分配的类型是动态类型?

不,如果foo是局部变量,那不是。

“dynamic”是一个编译时function。 这只是编译器的一个提示,意思是“在编译时不要尝试对此表达式进行类型分析;而是生成在运行时调用特殊版本编译器的代码”。

在运行时,局部变量foo只是object类型的局部变量,局部变量的内容是对Cat的引用。 编译器知道代码的作者想要在编译时避免对foo进行类型分析的事实已经丢失。

通过使用reflection检查方法上的编译器生成的属性,可以确定返回对象的方法是否实际返回动态。