【问题标题】:C# Exclamation Operator On Object [closed]对象上的 C# 感叹号运算符
【发布时间】:2017-03-14 18:56:08
【问题描述】:

在 C# 中,以下代码片段是做什么的?

1)

if (!object)
{
  //code
}

2)

if (object)
{
  //code
}

object 是一个类的实例,绝对不是bool。

1) 在 Java 中,尝试上述代码会使编译器发出错误。只有布尔变量可以用作 Condition_Block。这按预期工作。

2) 在 C++ 中,if (!object){/**/} 用于空值检查。

3) 在 C# 中,编译器不会发出任何错误并愉快地编译它。谷歌从未提及!运算符用于对象。它只给出布尔值的搜索结果。更何况落井下石,还给人家议论纷纷的结果?和 ??运营商,这些运营商可能在 30 到 40 年内无法提供给统一开发人员使用。仅支持 NET3.5 API。如果 !运算符在 C++ 中工作,为什么人们需要?和??。

编辑:完整代码。

using UnityEngine;
using System.Collections;

public class Foo : MonoBehaviour
{
    void Start ()
    {
        Foo a = new Foo();
        if (a)  Debug.Log("a");
        if (!a) Debug.Log("b");
    }
 }

它在执行时打印“b”。

【问题讨论】:

  • “在 c# 中,编译器不会发出任何错误并愉快地编译它”——不是我的编译器。但是你拒绝说“对象”是什么类型,所以你显然在你的问题中留下了一些不可或缺的东西。
  • P.S. ??、?. 和 ?:(你养成了排除重要信息的真正习惯,不是吗)做一些不同的事情。

标签: c# if-statement conditional-statements


【解决方案1】:

在 C# 中,if (!object) 将在三个实例中编译:

  1. 如果object 是bool 类型
  2. 如果已为 object 类型定义了 implicit operator bool 重载。
  3. 如果! 运算符已被object 类型重载。

一个重载!的例子:

class Test
{
    public int Value;

    public static bool operator ! (Test item)
    {
        return item.Value != 0;
    }
}

然后:

Test test = new Test();
Console.WriteLine(!test); // Prints "False"

test.Value = 1;
Console.WriteLine(!test); // Prints "True"

在 C# 中有两个实例可以编译 if (object):

  1. 如果object 是bool 类型。
  2. 如果已为 object 的类型定义了 implicit operator bool 重载。

implicit operator bool 的一个例子:

class Test
{
    public int Value;

    public static implicit operator bool(Test item)
    {
        return item.Value != 0;
    }
}

然后:

Test test = new Test();

Console.WriteLine(!test); // Prints "True"

if (test)
    Console.WriteLine("This is not printed");

test.Value = 1;

Console.WriteLine(!test); // Prints "False"

if (test)
    Console.WriteLine("This is printed");

【讨论】:

  • Edit 我错过了implicit operator bool - 添加到答案中。
  • @user2186597 如果删除隐式运算符,我发布的代码将无法编译(试试看!)。
  • @user2186597 你的类派生自MonoBehaviour,它实现了implicit operator bool,所以一切都解释清楚了。
猜你喜欢
  • 2012-01-27
  • 1970-01-01
  • 2013-02-19
  • 2022-01-15
  • 2017-10-08
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
相关资源
最近更新 更多