反映在一个动态类型,以告诉它是否是一个动态类型,开始 [英] Reflect on a dynamic type to tell if it was a dynamic type, to begin with

查看:168
本文介绍了反映在一个动态类型,以告诉它是否是一个动态类型,开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way that one can tell if the type that an object was assigned to, was a dynamic type?

例如:

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是一个局部变量,那么可以知道一个对象被分配给的类型是否是一个动态类型?

Is there a way that one can tell if the type that an object was assigned to was a dynamic type?

中。

dynamic是一个编译时功能。这只是对编译器的一个提示,意味着不要在编译时对此表达式进行类型分析;而是生成在运行时调用特殊版本的编译器。

"dynamic" is a compile-time feature. It's just a hint to the compiler that means "don't bother to try to do type analysis at compile time on this expression; instead, generate code that invokes a special version of the compiler at runtime".

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

At runtime, the local variable foo is just a local variable of type object, and the contents of the local variable are a reference to a Cat. The fact that the compiler knew that the author of the code wanted to avoid type analysis on foo at compile time has been lost.

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

It is possible to figure out whether a method that returns object is actually returning dynamic, by examining the compiler-generated attributes on the method using reflection.

这篇关于反映在一个动态类型,以告诉它是否是一个动态类型,开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆