我有一个类对象列表并想删除其中一项,但它不起作用:
我有一个类对象列表并想要删除一项,但是它没有成功:
class Person
{
public string name;
public Person(string s)
{
this.name = s;
}
}
void ABC()
{
List<Person> newPersonList = new List<Person>();
newPersonList.Add(new Person("A"));
newPersonList.Add(new Person("B"));
newPersonList.Add(new Person("C"));
newPersonList.Remove(A);
newPersonList.RemoveAt(1);
}
RemoveAt(1) 可以工作并删除 ID 为 1 的项。
我认为 Remove(A) 应该删除值为“A”的项目,但这并没有起作用。有人能解释一下吗?正确的按值删除方式是什么?
Remove(A);
应该发生什么?你没有声明A
。一般来说,你需要重写Person
中的Equals
或/和实现IEquatable<Person>
。 - Tim Schmelter