我在代码中为 IList 接口添加了众所周知的 RemoveAll 扩展方法,但尝试使用它的代码根本无法识别它。我的代码中没有任何错误,当我尝试在 IList 对象上调用扩展方法时,仅出现以下错误:
IList”不包含“RemoveAll”的定义,并且找不到接受“IList”类型的第一个参数的可访问扩展方法“RemoveAll”(您是否缺少 using 指令或程序集引用?)
扩展方法:
public static int RemoveAll<T>(this IList<T> iList, Predicate<T> match)
{
int count = 0;
for (int i = iList.Count - 1; i >= 0; i--)
{
if (match(iList[i]))
{
++count;
iList.RemoveAt(i);
}
}
return count;
}
来电:
List.RemoveAll(x => x.RequestDeletion);
RequestDeletion 是我的类 GameEntity 的一个属性。 我尝试删除所有对象的声明如下:
public IList List;
因为它是通过反射来实例化的:
List = (IList)Activator.CreateInstance(listType);
恐怕问题与声明为 IList 而不是 IList<..> 的对象有关,但我无法使用 CreateInstance 方法来做到这一点。 事实上,如果我尝试以下操作,它会起作用,但这不是我的目标: IList 测试 = new List(); test.RemoveAll(x => x.RequestDeletion);
我已经检查过:
恐怕问题与声明为 IList 而不是 IList<..> 的对象有关,但我无法使用 CreateInstance 方法来做到这一点。
你是对的,这就是问题所在 -
IList
不是继承自 IList<T>
,因此无法使用扩展方法。
我不知道为什么你不能用
IList<T>
创建通用的 CreateInstance
,你能详细说明一下吗?这应该是完全可行的,但也许您有一些非常具体的场景?
但是,如果您的对象实际上是
IList
(而不是通用对象),您可以将扩展方法签名更改为 public static int RemoveAll(this IList iList, Predicate<object> match)
,但这样您就会失去 T
的类型安全性。