在C#中检查对象是否是非特定泛型类型

EZL*_*ner 11 .net c# generics types

说我有以下课程:

public class General<T> { }
Run Code Online (Sandbox Code Playgroud)

我想知道一个对象是否属于那种类型.我知道我可以使用反射来找出该对象是否属于该泛型类型Type.GetGenericTypeDefinition,但我想避免这种情况.

是否有可能做某事obj is General<T>,或obj.GetType().IsAssignableFrom(typeof(General<T>))

我很惊讶我找不到类似的问题,尽管我在搜索中可能使用了错误的关键字.

dig*_*All 7

你可以这样做:

var obj = new General<int>();
var type = obj.GetType();
var isGeneral = 
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(General<>)) ||
type.GetBaseTypes().Any(x => x.IsGenericType && 
                             x.GetGenericTypeDefinition() == typeof(General<>));
Run Code Online (Sandbox Code Playgroud)

GetBaseTypes以下扩展方法在哪里:

public static IEnumerable<Type> GetBaseTypes(this Type type)
{
    if (type.BaseType == null) return type.GetInterfaces();

    return new []{type}.Concat(
           Enumerable.Repeat(type.BaseType, 1)
                     .Concat(type.GetInterfaces())
                     .Concat(type.GetInterfaces().SelectMany<Type, Type>(GetBaseTypes))
                     .Concat(type.BaseType.GetBaseTypes()));
}
Run Code Online (Sandbox Code Playgroud)

Slacks的回答

  • `GetGenericTypeDefinition()`抛出非泛型类型的异常.我正在阅读这个问题的方式,你应该能够为`int`调用它(并获得`false`),你应该能够为`I类调用它:General <int>`(并得到` TRUE`). (2认同)
  • 那个检查避免了我的`class I`的例外,但给出了错误的结果.`new I()是General <int>`会返回`true`,但你的检查不会. (2认同)

归档时间:

查看次数:

4573 次

最近记录:

11 年,4 月 前