覆盖 == 运算符.如何与空值进行比较?
- 作者: 混合面饽饽
- 来源: 51数据库
- 2022-10-20
问题描述
可能的重复:
如何检查空值在没有无限递归的=="运算符重载中?
对此可能有一个简单的答案……但我似乎无法回答.这是一个简化的例子:
There is probably an easy answer to this...but it seems to be eluding me. Here is a simplified example:
public class Person
{
public string SocialSecurityNumber;
public string FirstName;
public string LastName;
}
假设对于这个特定的应用程序,如果社会安全号码匹配,并且两个名字匹配,那么我们指的是同一个人".
Let's say that for this particular application, it is valid to say that if the social security numbers match, and both names match, then we are referring to the same "person".
public override bool Equals(object Obj)
{
Person other = (Person)Obj;
return (this.SocialSecurityNumber == other.SocialSecurityNumber &&
this.FirstName == other.FirstName &&
this.LastName == other.LastName);
}
为了保持一致,我们也为团队中不使用 .Equals 方法的开发人员覆盖了 == 和 != 运算符.
To keep things consistent, we override the == and != operators, too, for the developers on the team who don't use the .Equals method.
public static bool operator !=(Person person1, Person person2)
{
return ! person1.Equals(person2);
}
public static bool operator ==(Person person1, Person person2)
{
return person1.Equals(person2);
}
很好很花哨,对吧?
但是,当 Person 对象为 null 时会发生什么?
However, what happens when a Person object is null?
你不能写:
if (person == null)
{
//fail!
}
因为这将导致 == 运算符覆盖运行,并且代码将失败:
Since this will cause the == operator override to run, and the code will fail on the:
person.Equals()
方法调用,因为您不能在空实例上调用方法.
method call, since you can't call a method on a null instance.
另一方面,您无法在 == 覆盖中明确检查此条件,因为它会导致无限递归(和堆栈溢出 [dot com])
On the other hand, you can't explicitly check for this condition inside the == override, since it would cause an infinite recursion (and a Stack Overflow [dot com])
public static bool operator ==(Person person1, Person person2)
{
if (person1 == null)
{
//any code here never gets executed! We first die a slow painful death.
}
return person1.Equals(person2);
}
那么,您如何覆盖 == 和 != 运算符以实现值相等并仍然考虑空对象?
So, how do you override the == and != operators for value equality and still account for null objects?
我希望答案不是那么简单.:-)
I hope that the answer is not painfully simple. :-)
推荐答案
使用 object.ReferenceEquals(person1, null) 或新的 is 运算符 而不是 == 运算符:
Use object.ReferenceEquals(person1, null) or the new is operator instead of the == operator:
public static bool operator ==(Person person1, Person person2)
{
if (person1 is null)
{
return person2 is null;
}
return person1.Equals(person2);
}
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
