【发布时间】:2014-01-08 12:34:41
【问题描述】:
在 Java 中,当您想通过 remove() 方法从通用 Collection 中正确删除对象时,您必须实现可以在 Eclipse 中自动生成的 equals(Object o) 和 remove() 方法。该方法的示例如下所示 --->。
如何在 C# 中自动生成该方法(Visual Studio,我在 VS2013)?
也许没有必要让
List.Remove()方法正常工作?如果不可能自动引用
Equals方法应该是什么样子?我的意思是它应该是什么样子。Equals()方法是否甚至在List.Remove()中使用,如果是这样,如果我们比较相同的对象(内存中的相同地址),您能否告诉我应该如何实现Equals()以返回 true
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((centerPanel == null) ? 0 : centerPanel.hashCode());
result = prime * result + ((lowerPanel == null) ? 0 : lowerPanel.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
LayoutDemo other = (LayoutDemo) obj;
if(centerPanel == null) {
if(other.centerPanel != null)
return false;
} else if(!centerPanel.equals(other.centerPanel))
return false;
if(lowerPanel == null) {
if(other.lowerPanel != null)
return false;
} else if(!lowerPanel.equals(other.lowerPanel))
return false;
return true;
}
【问题讨论】:
-
自动是什么意思?甚至 eclipse 也不知道你想如何实现这些方法,那么你的自定义对象的相等意味着什么。如果你只想创建方法体,让你的类实现
IEqualityComparer。如果单击界面下方的红色错误线,Visual Studio 会建议自动创建它们。但它们将只包含throw new NotImplementedException();。 -
@TimSchmelter 它确实知道,上面的例子。
-
所以 Eclipse 将你的类的所有属性添加到
Equals和GetHashCode或者只是一个或没有?什么是上面自动生成的,一切?Equals和GethashCode对于复杂的对象来说并不是微不足道的。 -
@TimSchmelter Is
Equals()方法甚至在List.Remove()中使用如果是这样,如果我们比较相同的对象(内存中的相同地址),你能否告诉我如何实现Equals()以返回 true ) -
Equals用于List.Remove并通过引用比较两个对象:Object.ReferenceEquals(obj1, obj2)。首先阅读文档总是值得的。您将在备注部分找到相关信息。
标签: c# .net visual-studio list