Is there a way to determine if a generic type is built from a specific generic type definition?

后端 未结 4 1346
忘掉有多难
忘掉有多难 2020-12-18 08:45

I\'ve got a generic method:

Func, bool> CreateFunction()

where T can be any number of diff

4条回答
  •  暖寄归人
    2020-12-18 09:19

    You can avoid using ugly and potentially risky type name string checking using the IsGenericType and GetGenericTypeDefinition members, as follows:

    var type = typeof (T);
    if (typeof (IDictionary).IsAssignableFrom(type))
    {
        //non-generic dictionary
    }
    else if (type.IsGenericType &&
             type.GetGenericTypeDefinition() == typeof (IDictionary<,>))
    {
        //generic dictionary interface
    }
    else if (type.GetInterfaces().Any(
                i => i.IsGenericType &&
                     i.GetGenericTypeDefinition() == typeof (IDictionary<,>)))
    {
        //implements generic dictionary
    }
    

提交回复
热议问题