Resharper - 生成包括基类成员在内的相等成员

sve*_*vit 8 .net c# resharper equality

是否有可能为类生成平等成员,该类还包括其基类的成员?

例如 - 抽象基类:

public abstract class MyBaseClass
{
    public int Property1;
}
Run Code Online (Sandbox Code Playgroud)

其他课程:

public class MyOtherClass: MyBaseClass
{
    public int Property2 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

如果我使用Resharper自动生成相等成员,我只能基于MyOtherClass.Property2属性获得相等,而不是基于Property1其基类.

ang*_*son 11

首先在基类中生成相等性检查,然后在后代中进行.

在后代,差异将在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;
}
Run Code Online (Sandbox Code Playgroud)

使用基类中的相等检查:

public bool Equals(MyOtherClass other)
{
    if (ReferenceEquals(null, other))
        return false;
    if (ReferenceEquals(this, other))
        return true;
    return base.Equals(other) && other.Property2 == Property2;
}
Run Code Online (Sandbox Code Playgroud)

注意添加的调用base.Equals(other),因此负责基类中的属性.

请注意,如果你反过来这样做,你首先将等式检查添加到后代,然后将它们添加到基类,然后ReSharper不会去追溯修改后代中的代码,你必须重新生成它(删除+生成),或手动修改代码.

  • 要重新生成,您不需要删除.生成时,可以选择替换现有成员. (3认同)