簡體   English   中英

Resharper - 生成包括基類成員在內的相等成員

[英]Resharper - generate equality members including base class members

是否有可能為類生成平等成員,該類還包括其基類的成員?

例如 - 抽象基類:

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不會去追溯修改后代中的代碼,您必須重新生成它(刪除+生成),或手動修改代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM