Mik*_*sen 6 .net c# operator-overloading
我有一个看起来像这样的对象:
public class Tags
{
int mask;
public static bool operator !=(Tags x, Tags y)
{
return !(x == y);
}
public static bool operator ==(Tags x, Tags y)
{
return x.mask == y.mask;
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于将实例相互比较,但我也希望能够处理如下表达式:
if(tags1 == null)
Run Code Online (Sandbox Code Playgroud)
这样做会导致以下行出现异常:
return x.mask == y.mask;
Run Code Online (Sandbox Code Playgroud)
既然y是null.
我已经尝试将此功能更改为:
public static bool operator ==(Tags x, Tags y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.mask == y.mask;
}
Run Code Online (Sandbox Code Playgroud)
但是,这会创建堆栈溢出,因为实现使用自己的重写比较运算符.
让==操作员处理比较的诀窍是什么null?谢谢!
根据指南:
public static bool operator ==(Tags a, Tags b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.mask == b.mask;
}
Run Code Online (Sandbox Code Playgroud)
而不是x == null,你可以使用(object)x == null或Object.ReferenceEquals(x, null):
public static bool operator ==(Tags x, Tags y)
{
if ((object)x == null && (object)y == null) return true;
if ((object)x == null || (object)y == null) return false;
return x.mask == y.mask;
}
Run Code Online (Sandbox Code Playgroud)
但你也应该实现Equals和GetHashCode:
public override bool Equals(object obj)
{
return this.Equals(obj as Tags);
}
public bool Equals(Tags tags)
{
return (object)tags != null && this.mask == tags.mask;
}
public override int GetHashCode()
{
return this.mask.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
现在operator ==可以简单地写:
public static bool operator ==(Tags x, Tags y)
{
return (object)x != null ? x.Equals(y) : (object)y == null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
940 次 |
| 最近记录: |