我可以创建列表并使用RemoveAll删除一些元素,但我需要使用接口来执行此操作。怎么做? 列表元素是String。
答案 0 :(得分:1)
这就是你问的问题:
// An interface
public interface IMySelector
{
bool IDontLike(string str);
}
// A class implementing the interface
public class MySelector : IMySelector
{
public bool IDontLike(string str)
{
if (str.StartsWith("foo"))
{
return true;
}
return false;
}
}
List<string> list = new List<string> { "foo1", "foo2", "bar1", "bar2" };
// Using the interface
IMySelector selector = new MySelector();
// Begin from last, it will be faster to remove
for (int i = list.Count - 1; i >= 0; i--)
{
// Your condition
if (selector.IDontLike(list[i]))
{
list.RemoveAt(i);
}
}
有一个接口,一个实现接口的类和使用该接口选择要删除的元素的代码。请注意我如何从底部到顶部删除元素。它更快,它需要少一行代码:-)(如果您有 [0... list.Count)
,那么您将拥有if (selector...) { list.RemoveAt(1); i--; }
)
作为一个小注释,在C#中,您通常使用委托而不是单方法接口。
使用IEquatable<T>
public class MySelector : IEquatable<string>
{
public bool Equals(string str)
{
// Strange concept of equality... All the
// words that start with foo are equal :-)
if (str.StartsWith("foo"))
{
return true;
}
return false;
}
}
List<string> list = new List<string> { "foo1", "foo2", "bar1", "bar2" };
// Using the interface
IEquatable<string> selector = new MySelector();
// Begin from last, it will be faster to remove
for (int i = list.Count - 1; i >= 0; i--)
{
// Your condition
if (selector.Equals(list[i]))
{
list.RemoveAt(i);
}
}
答案 1 :(得分:0)
编写扩展方法。称之为RemoveAll<TItem>
。您希望扩展接口IList<TItem>
,因此请相应地选择this
- 标记的参数。还要创建Func<TItem, bool>
参数。在方法体foreach
中,使用委托实例,并调用IList<>.Remove
实例方法。
由于这是家庭作业,我想我提供了足够的细节。