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不会去追溯修改后代中的代码,你必须重新生成它(删除+生成),或手动修改代码.
| 归档时间: |
|
| 查看次数: |
1591 次 |
| 最近记录: |