3 回答

TA貢獻1802條經(jīng)驗 獲得超10個贊
如果要檢查它是否是泛型類型的實例:
return list.GetType().IsGenericType;
如果你想檢查它是否是通用的List<T>:
return list.GetType().GetGenericTypeDefinition() == typeof(List<>);
正如Jon指出的那樣,這會檢查確切的類型等價。返回false并不一定意味著list is List<T>返回false(即,不能將對象分配給List<T>變量)。

TA貢獻1898條經(jīng)驗 獲得超8個贊
您可以使用動態(tài)althougth來使用更短的代碼,這可能比純反射更慢:
public static class Extension
{
public static bool IsGenericList(this object o)
{
return IsGeneric((dynamic)o);
}
public static bool IsGeneric<T>(List<T> o)
{
return true;
}
public static bool IsGeneric( object o)
{
return false;
}
}
var l = new List<int>();
l.IsGenericList().Should().BeTrue();
var o = new object();
o.IsGenericList().Should().BeFalse();
- 3 回答
- 0 關(guān)注
- 662 瀏覽
添加回答
舉報