【问题标题】:Is it possible to modify the boolean value returned when checked if an instance of an object is null?检查对象的实例是否为空时,是否可以修改返回的布尔值?
【发布时间】:2011-07-27 20:16:06
【问题描述】:

我想知道是否可以修改检查对象实例是否为空时返回的布尔值,例如(我知道这是错误且不完整的,只是想给你一个参考):

主要:

SuperObject obj = new SuperObject();

if (obj == null) Console.WriteLine("It is null lol!");

超级对象:

public bool destroyed = false;

public static bool operator ==(SuperObject A, object B)
{
if (A != null && B == null && destroyed == true)
      return true;
}

因此,如果检查了表达式 (A == null) 并且 A 不为 null 但 A.destroyed 为 TRUE,它将返回 (A == null) 为 TRUE。

基本上我希望 (A == null) 在以下情况下为 TRUE: A 真的为 null 或 A.destroyed = null;其他比较的默认值。

【问题讨论】:

  • 从维护/可读性的角度来看,这听起来是个坏主意,即使它是可能的

标签: c# null operator-keyword


【解决方案1】:

我建议这样做:

public static bool IsDestroyed(SuperObject a) {
    return (a == null || a.destroyed);
}

你的方式会让新开发者非常困惑。

【讨论】:

  • OP 的方式会让任何开发者感到困惑,而不仅仅是新开发者!
  • 感谢您的推荐。
猜你喜欢
  • 1970-01-01
  • 2012-10-29
  • 2013-04-02
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 2016-08-22
  • 2011-09-07
相关资源
最近更新 更多