是否可以为类生成相等成员,其中还包括来自其基类的成员?
例如——抽象基类:
public abstract class MyBaseClass
{
public int Property1;
}
其他类:
public class MyOtherClass: MyBaseClass
{
public int Property2 {get; set;}
}
如果我使用 Resharper 自动生成相等成员,我将仅基于 MyOtherClass.Property2
属性而不是基于其基类的 Property1
获得相等性。
最佳答案
首先在基类中生成相等性检查,然后在后代中进行。
在后代中,差异将在 public bool Equals(MyOtherClass other)
类中。
在基类中没有相等性检查:
public bool Equals(MyOtherClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return other.Property2 == Property2;
}
在基类中进行相等性检查:
public bool Equals(MyOtherClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return base.Equals(other) && other.Property2 == Property2;
}
请注意对 base.Equals(other)
的添加调用,因此它负责基类中的属性。
注意,如果反着来,先给后代添加相等性检查,再给基类添加,那么ReSharper就不去了,追溯修改代码在后代中,您要么必须重新生成它(删除+生成),要么手动修改代码。
关于c# - Resharper - 生成相等成员包括基类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4875416/