GenericType上的IsAssignableFrom

Tre*_*ent 3 c# reflection

不确定我是否可以这样做,但我正在尝试查看类型是否继承了具有通用约束的其他类型.

这是我想要找到的课程:

public class WorkoutCommentStreamMap : ClassMapping<WorkoutCommentStream>...
Run Code Online (Sandbox Code Playgroud)

这是测试

var inheritableType = typeof(NHibernate.Mapping.ByCode.Conformist.ClassMapping<>);
var isMappedObject = inheritableType.IsAssignableFrom(typeof(WorkoutCommentStreamMap));
Run Code Online (Sandbox Code Playgroud)

如果我将第一行更改为下面,它可以工作.但这违背了我的例子的目的.我的后备工作是在我想要查找的所有对象上放置一个自定义的非泛型接口并使用相同的调用.

var inheritableType = typeof(NHibernate.Mapping.ByCode.Conformist.ClassMapping<WorkoutCommentStream>);
Run Code Online (Sandbox Code Playgroud)

Red*_*dog 7

泛型类型定义和封闭泛型类型之间没有继承关系.因此,IsAssignableFrom不会起作用.

但是,我使用这个小扩展方法来实现你的后续:

public static bool IsGenericTypeOf(this Type t, Type genericDefinition)
{
    Type[] parameters = null;
    return IsGenericTypeOf(t, genericDefinition, out parameters);
}

public static bool IsGenericTypeOf(this Type t, Type genericDefinition, out Type[] genericParameters)
{
    genericParameters = new Type[] { };
    if (!genericDefinition.IsGenericType)
    {
        return false;
    }

    var isMatch = t.IsGenericType && t.GetGenericTypeDefinition() == genericDefinition.GetGenericTypeDefinition();
    if (!isMatch && t.BaseType != null)
    {
        isMatch = IsGenericTypeOf(t.BaseType, genericDefinition, out genericParameters);
    }
    if (!isMatch && genericDefinition.IsInterface && t.GetInterfaces().Any())
    {
        foreach (var i in t.GetInterfaces())
        {
            if (i.IsGenericTypeOf(genericDefinition, out genericParameters))
            {
                isMatch = true;
                break;
            }
        }
    }

    if (isMatch && !genericParameters.Any())
    {
        genericParameters = t.GetGenericArguments();
    }
    return isMatch;
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

Nullable<int> value = 9;
Assert.IsTrue(value.GetType().IsGenericTypeOf(typeof(Nullable<>)));
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

您可以使用BaseType,IsGenericTypeGetGenericTypeDefinition递归了层次结构,并设法找到它:

public bool IsClassMapping(Type t)
{
    while (t != null)
    {
        if (t.IsGenericType &&
            t.GetGenericTypeDefinition() == typeof(ClassMapping<>))
        {
            return true;
        }
        t = t.BaseType;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)