Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检测类型是否实现ICollection<;T>;_C#_.net_Vb.net_Reflection - Fatal编程技术网

C# 检测类型是否实现ICollection<;T>;

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

我试图检查类型是否实现了泛型ICollection接口,因为这是我的任何泛型集合的基础接口

下面的代码不起作用

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
时,这才有效。

这是正确答案;我已经测试过了