c# - Resharper - 生成相等成员包括基类成员

标签 c# .net resharper equality

是否可以为类生成相等成员,其中还包括来自其基类的成员?

例如——抽象基类:

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/

相关文章:

c# - 使用 linq to excel 从多个 excel 表中读取数据 (http ://code. google.com/p/linqtoexcel/)

c# - 如何在 Ef Core 中添加包含在通用存储库模式中?

c# - 更新多行

c# - .NET 对象最灵活的序列化是什么,但实现起来很简单?

c# - 启动和等待多个线程 - Resharper 提示修改后的闭包

c# - 有没有办法在 ASP 中为 Cellspacing 使用非 Int32 值?

c# - 查找链接元素

c# - 仅使用 LINQ 对包含数字属性的对象集合求和

.net - ReSharper 和 var

asp.net-mvc-3 - 有什么方法可以让 VS 识别 ReSharper razor 错误并导致编译失败