C# 检测类型是否实现ICollection<;T>;
我试图检查类型是否实现了泛型ICollection接口,因为这是我的任何泛型集合的基础接口 下面的代码不起作用C# 检测类型是否实现ICollection<;T>;,c#,.net,vb.net,reflection,C#,.net,Vb.net,Reflection,我试图检查类型是否实现了泛型ICollection接口,因为这是我的任何泛型集合的基础接口 下面的代码不起作用 GetType(ICollection(Of)).IsAssignableFrom( objValue.GetType().GetGenericTypeDefinition()) 检测类型是否实现泛型接口的好方法是什么; CustomCollection c = new CustomCollection(); bool implementICollection = c.Ge
GetType(ICollection(Of)).IsAssignableFrom(
objValue.GetType().GetGenericTypeDefinition())
检测类型是否实现泛型接口的好方法是什么;
CustomCollection c = new CustomCollection();
bool implementICollection = c.GetType().GetInterfaces()
.Any(x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(ICollection<>));
bool implementICollection=c.GetType().GetInterfaces()
.Any(x=>x.IsGenericType&&
x、 GetGenericTypeDefinition()==typeof(ICollection));
其他方法的替代方法如下:
if (MyObject is ICollection<T>)
...
if(MyObject是ICollection)
...
注意:只有在编译时知道
T
时,这才有效。这是正确答案;我已经测试过了