简体   繁体   中英

Dynamic does not contain a definition for GetType()

I have a variable of type dynamic in my code what I am trying to do is get the type of the assigned object but it seems that there are no properties or methods available in the dynamic field.

My code is something like:

dynamic readings;

private void method()
{
    Type type= readings.GetType();
}

Am I doing something wrong here?

Reference for using GetType:

How do I check type of dynamic datatype at runtime?

just cast it to object :

Type type = ((object)readings).GetType();

Being dynamic means that all calls can be intercepted, but that's a compiler trick, not an inherent feature of the type. Casting it to object means that the compiler stops doing that . Behind the scenes, dynamic is just a fancy word for object anyway .

Note, however, that it is usually a bad idea to mix reflection ( GetType() ) and dynamic ; while objects can work as dynamic (by re-exposing the reflection API as dynamic ), this is not always the case, and many (most?) implementations of dynamic are presenting entirely artificial members that do not exist in terms of reflection. That's kinda the main point of dynamic , with "oh, it also lets you be lazy and talk to types without knowing their type" just a handy side-effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM