我想知道是否可以使用扩展方法从通用List中删除相同类型的所有对象.像这样的代码:
public static Remove<T>(this List<[any type]> list)
{
// some code to remove the objects of type T from the list
}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下代码执行此操作:
public static Remove<T, K>(this List<K> list)
{
// some code to remove the objects of type T from the List<K>
}
Run Code Online (Sandbox Code Playgroud)
但我想只使用类型(T),而不需要指定任何类型K.通过这样做,用户可以使用此扩展方法,只需写下:
List<object> list = new List<object>();
list.Add(1);
list.Add("text");
// remove all int type objects from the list
list.Remove<int>();
Run Code Online (Sandbox Code Playgroud)
我可以使用一种扩展方法来完成与上面代码完全相同的操作.
最好的祝福
不知道这是否会工作或不...但它是值得一试(我不能编译仔细检查):
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);
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你需要的东西多一点严格的(而不是可强制转换为任何类型的对象),你可以尝试:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
理论上,你应该好好去.List<T>
实现的IList
实现IEnumerable
.IList提供了Remove()
IEnumerable提供的扩展方法.
请注意,根据集合中的类型,这肯定会产生意外结果.我同意Jon Skeet ......这绝对是丑陋的.
归档时间: |
|
查看次数: |
4194 次 |
最近记录: |