我有一个通用列表:
IList<T> myobj = new List<T>();
如何检查 myobj
是通用列表(又名 IList<T>
)?
我试过了,没有成功:
if(myobj.GetType().IsGenericType && myobj is IList) //second exp is never true
此时我不想知道 T 的类型,我只想知道是否 myobj
是一个列表。
---编辑--------------------
'myobj' 一直为 null,这导致它无法通过所有检查。对不起这是我的错。事实证明,我的问题中描述的解决方案(与您的一些答案类似)效果很好。不过我还没有尝试过其他答案。
我正在做以下事情:
PropertyType propInf = ...
var myobj = propInf.GetValue(parentobj,null);//was always null
最佳答案
你试过了吗(myObj is IList)
:
public static void Main(string[] args)
{
List<int> foo = new List<int>();
bool b = foo is IList; // true
}
.NET 中的大多数通用集合接口(interface)都有对应的非通用接口(interface)(例如 IList
和 IList<T>
)
http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx
关于C# - 如何知道对象是否是 ICollection 的衍生物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8070306/