获取通用接口的类型?

Gui*_*shy 14 c# generics

我有一个这样的通用接口:

public interface IResourceDataType<T>
{
    void SetResourceValue(T resValue);
}
Run Code Online (Sandbox Code Playgroud)

然后我得到了这个实现我的接口的类:

public class MyFont : IResourceDataType<System.Drawing.Font>
{
    //Ctor + SetResourceValue + ...
}
Run Code Online (Sandbox Code Playgroud)

最后我得到了一个:

var MyType = typeof(MyFont);
Run Code Online (Sandbox Code Playgroud)

我现在想System.Drawing.Font从MyType中获取Type!目前,我得到了这段代码:

if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
    //If test is OK
}
Run Code Online (Sandbox Code Playgroud)

但是我没有设法在这里"提取"我的类型...我尝试了一些事情GetGenericArguments()和其他事情,但他们要么不编译或返回空值/列表...我该怎么办?

编辑:这是适合我的代码的解决方案,为那些将得到同样问题的人:

if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
    foreach (Type type in MyType.GetInterfaces())
    {
        if (type.IsGenericType)
            Type genericType = type.GetGenericArguments()[0];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 11

由于您的MyFont类只实现了一个接口,您可以编写:

Type myType = typeof(MyFont).GetInterfaces()[0].GetGenericArguments()[0];
Run Code Online (Sandbox Code Playgroud)

如果您的类实现了多个接口,则可以使用您正在查找的接口的错位名称调用GetInterface()方法:

Type myType = typeof(MyFont).GetInterface("IResourceDataType`1")
                            .GetGenericArguments()[0];
Run Code Online (Sandbox Code Playgroud)


Jac*_*ins 5

var fontTypeParam = typeof(MyFont).GetInterfaces()
    .Where(i => i.IsGenericType)
    .Where(i => i.GetGenericTypeDefinition() == typeof(IResourceDataType<>))
    .Select(i => i.GetGenericArguments().First())
    .First()
    ;
Run Code Online (Sandbox Code Playgroud)

这可以解决您对重命名界面的担忧。没有字符串文字,因此在 Visual Studio 中重命名应该会更新您的搜索表达式。