测试对象是否是C#中的泛型类型

如果对象是泛型类型,我想执行测试。我试过以下但没有成功:


public bool Test()

{

    List<int> list = new List<int>();

    return list.GetType() == typeof(List<>);

}

我做错了什么,我该如何进行这项测试?


梦里花落0921
浏览 614回答 3
3回答

守候你守候我

如果要检查它是否是泛型类型的实例:return list.GetType().IsGenericType;如果你想检查它是否是通用的List<T>:return list.GetType().GetGenericTypeDefinition() == typeof(List<>);正如Jon指出的那样,这会检查确切的类型等价。返回false并不一定意味着list is List<T>返回false(即,不能将对象分配给List<T>变量)。

汪汪一只猫

您可以使用动态althougth来使用更短的代码,这可能比纯反射更慢:public static class Extension{&nbsp; &nbsp; public static bool IsGenericList(this object o)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;return IsGeneric((dynamic)o);&nbsp; &nbsp; }&nbsp; &nbsp; public static bool IsGeneric<T>(List<T> o)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;return true;&nbsp; &nbsp; }&nbsp; &nbsp; public static bool IsGeneric( object o)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}var l = new List<int>();l.IsGenericList().Should().BeTrue();var o = new object();o.IsGenericList().Should().BeFalse();
打开App,查看更多内容
随时随地看视频慕课网APP