![](/img/trans.png)
[英]How to retrieve the argument of a generic base class at compile time? (i.e., without using Reflection)
[英]How to retrieve generic argument with reflection
如果我有这样的课
interface IDeclaration<T> {...}
我应该如何实现检查我的特定类的实例是否从IDeclaration<T>
派生,如果是的话-在我们的特殊情况下,类型T
是什么。
先感谢您
IDeclaration
是一个接口,而不是一个类。 类可以实现此接口,而不是从其派生 。
要检查特定对象是否实现IDeclaration<T>
接口,可以在该实例类型上调用GetInterfaces
方法,然后搜索该特定接口,如下所示:
var instance = ...
var @interface =
instance.GetType()
.GetInterfaces()
.FirstOrDefault(i =>
i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof (IDeclaration<>));
bool is_IDeclaration = @interface != null;
要获取通用类型参数( T
),可以使用GetGenericArguments
方法,如下所示:
if (is_IDeclaration)
{
var typeof_T = @interface.GetGenericArguments()[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.