我有一个通用的接口,就像这样:
public interface IResourceDataType<T>
{
void SetResourceValue(T resValue);
}
接下来,我创建了一个实现我的接口的类:
public class MyFont : IResourceDataType<System.Drawing.Font>
{
//Ctor + SetResourceValue + ...
}
最后,我获得了一个:
var MyType = typeof(MyFont);
我现在想从MyType获取System.Drawing.Font
类型!目前,我有以下代码:
if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
//If test is OK
}
但是我无法在这里“提取”我的类型...
我尝试了一些使用GetGenericArguments()
和其他方法的东西,但它们要么不能编译,要么返回null值/列表...
我该怎么做?
编辑: 以下是适用于我的代码的解决方案,对于那些遇到相同问题的人:
if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
foreach (Type type in MyType.GetInterfaces())
{
if (type.IsGenericType)
Type genericType = type.GetGenericArguments()[0];
}
}
}