简体   繁体   English

Dynamic 不包含 GetType() 的定义

[英]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.我的代码中有一个动态类型的变量,我想做的是获取分配的 object 的类型,但动态字段中似乎没有可用的属性或方法。

My code is something like:我的代码是这样的:

dynamic readings;

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

Am I doing something wrong here?我在这里做错了吗?

Reference for using GetType:使用 GetType 的参考:

How do I check type of dynamic datatype at runtime? 如何在运行时检查动态数据类型的类型?

just cast it to object :只需将其转换为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. dynamic意味着所有调用都可以被拦截,但这是一个编译器技巧,而不是该类型的固有特性。 Casting it to object means that the compiler stops doing that .将其转换为object意味着编译器停止这样做 Behind the scenes, dynamic is just a fancy word for object anyway .在幕后,无论如何dynamic只是object的一个花哨的词。

Note, however, that it is usually a bad idea to mix reflection ( GetType() ) and dynamic ;但是请注意,混合反射( GetType() )和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.虽然对象可以作为dynamic对象工作(通过将反射 API 重新暴露为dynamic对象),但情况并非总是如此,并且许多(大多数?) dynamic对象的实现都呈现出完全人为的成员,这些成员在反射方面并不存在 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.这就是dynamic的要点,“哦,它也让你变得懒惰并在不知道类型的情况下与类型交谈”只是一个方便的副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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