2

如果传递的类型可分配给(派生自)开放(无界)泛型类型的闭包,我需要一个返回 true 的方法。该方法应按以下方式工作:

OpenGenericIsAssignableFrom(typeof(ICollection<>), typeof(IList<String>))

应该返回真。

4

2 回答 2

3

为什么不简单地关闭开放的泛型类型,看看它是否可以从封闭的类型中获取?问题是用相同的参数关闭它可能无效,所以你需要抓住它

private static bool OpenGenericIsAssignableFrom(
    Type openGenericType, 
    Type typeToCheck)
{
    if (!openGenericType.IsGenericType || typeToCheck == null) return false;

    if(typeToCheck.IsGenericType)
    {
        var typeArgs = typeToCheck.GetGenericArguments();
        if (typeArgs.Length == openGenericType.GetGenericArguments().Length)
        {
            try
            {
              var closed = openGenericType.MakeGenericType(typeArgs);
              return closed.IsAssignableFrom(typeToCheck);
            }
            catch
            {
              //violated type contraints
              return false
            }
        }
    }
    else 
    {
        return OpenGenericIsAssignableFrom(openGenericType, typeToCheck.BaseType) 
              || typeToCheck.GetInterfaces()
                    .Any(i=> OpenGenericIsAssignableFrom(openGenericType,i));
    }
}
于 2012-06-29T11:59:59.633 回答
2

扩展检查类是否派生自泛型类,这是一个可能的解决方案:

        private static bool OpenGenericIsAssignableFrom1(Type openGenericType, Type typeToCheck)
        {
            return typeToCheck != null && typeToCheck != typeof(Object) && // Terminate recursion
                ((typeToCheck.IsGenericType && (typeToCheck.GetGenericTypeDefinition() == openGenericType)) || // typeToCheck is as closure of openGenericType
                OpenGenericIsAssignableFrom(openGenericType, typeToCheck.BaseType) || // typeToCheck is the subclass of a closure of openGenericType
                typeToCheck.GetInterfaces().Any(interfaceType => OpenGenericIsAssignableFrom(openGenericType, interfaceType))); // typeToCheck inherits from an interface which is the closure of openGenericType
        }
于 2012-06-29T11:46:40.723 回答