从List& T& gt;中删除某种类型的对象.在C#中使用扩展方法? [英] Remove objects of some kind of type from a List<T> in C# using extension methods?
问题描述
我想知道是否有可能使用扩展方法从通用列表中删除同一种类的所有对象.像这样的代码:
I wonder if its possible to remove all the objects from the same kind from a generic List using extension methods. something like this code:
public static Remove<T>(this List<[any type]> list)
{
// some code to remove the objects of type T from the list
}
我可以使用以下代码来做到这一点:
I can do this by using the following code:
public static Remove<T, K>(this List<K> list)
{
// some code to remove the objects of type T from the List<K>
}
但是我只想在类型(T)上使用,而无需指定任何类型K.通过这样做,用户可以通过简单地编写以下代码来使用此扩展方法:
but I want to just use on type (T), without need to specify any type K. by doing that the user can use this extension method by simply write this:
List<object> list = new List<object>();
list.Add(1);
list.Add("text");
// remove all int type objects from the list
list.Remove<int>();
我真正需要的是一种扩展方法,我可以使用它来做与上面的代码完全一样的事情.
a extension method which I can use to do something exactly like the above code is what I really need here.
最诚挚的问候
推荐答案
不确定是否可行...但是值得一试(我无法进行仔细检查):
Not sure if this will work or not...but it's worth a shot (I can't compile to double check):
public static void Remove<T>(this IList list)
{
if(list != null)
{
var toRemove = list.OfType<T>().ToList();
foreach(var item in toRemove)
list.Remove(item);
}
}
或者,如果您需要更严格的要求(而不是任何可以强制转换为类型的对象),则可以尝试:
Or if you need something a little more strict (rather than any object that can be cast to the type), you could try:
public static void Remove<T>(this IList list)
{
if(list != null)
{
var toRemove = list.Where(i => typeof(i) == typeof(T)).ToList();
foreach(var item in toRemove)
list.Remove(item);
}
}
从理论上讲,您应该很好. List< T>
实现了 IList
,后者实现了 IEnumerable
.IList提供 Remove()
,而IEnumerable提供扩展方法.
In theory, you should be good to go. List<T>
implements IList
which implements IEnumerable
. IList provides Remove()
and IEnumerable provides the extension method.
请注意,根据集合中的类型,这绝对可能会产生意想不到的结果.我同意乔恩·斯基特(Jon Skeet)的观点,这绝对是丑陋的.
Be aware that this could most definitely produce unexpected results depending on the types in the collection. I agree with Jon Skeet...it's most definitely ugly.
这篇关于从List& T& gt;中删除某种类型的对象.在C#中使用扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!