c# - 为什么 C# 中的 1 && 2 是假的?

标签 c# boolean boolean-operations

I got frustated with my other question .所以我写了这个例子。

In C the below is true. See demo

int main()
{
printf("%d", 1 && 2);
return 0;
}

输出:

1

在 C# 中。这是错误的。为什么这是错误的? 另外我不明白为什么我需要在这个例子中创建 bool 运算符而不是我的其他问题中的那个,但没关系。为什么下面是假的?这对我来说毫无意义。

顺便说一句,描述了使以下错误的逻辑here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyInt a=1, b=2;
            bool res=a && b;
            Console.WriteLine("result is {0}", res);
        }

        class MyInt
        {
            public int val;
            public static bool operator true(MyInt t) { return t.val != 0; }
            public static bool operator false(MyInt t) { return t.val == 0; }
            public static MyInt operator &(MyInt l, MyInt r) { return l.val & r.val; }
            public static MyInt operator |(MyInt l, MyInt r) { return l.val | r.val; }
            public static implicit operator MyInt(int v) { return new MyInt() { val = v }; }
            public static implicit operator bool(MyInt t) { return t.val != 0; }
        }
    }
}

最佳答案

C 中没有bool。约定是 0false!= 0trueif 语句以完全相同的方式处理条件表达式结果。

C++ 中引入了 bool。但它兼容旧规则,0被当作falsefalse被当作0,并且有隐式转换在 intbool 之间。

在 C# 中情况不同:有 boolint 并且它们不能相互转换。这就是 C# 标准所说的。期间。

因此,当您尝试重新实现 boolint 兼容性时,您犯了一个错误。您使用 && 这是逻辑运算符,但在 C# 中您不能覆盖它,只能覆盖按位实现的 &。 1 & 2 == 0 == false!在这里!

您甚至不应该重载按位运算符,为了保持兼容性,您只需保留 operator truefalse

此代码如您所愿:

class Programx
{
    static void Main(string[] args)
    {
        MyInt a = 1, b = 2;
        bool res = a && b;
        Console.WriteLine("result is {0}", res);
    }

    class MyInt
    {
        public int val;
        public static bool operator true(MyInt t)
        {
            return t.val != 0;
        }
        public static bool operator false(MyInt t)
        {
            return t.val == 0;
        }
        public static implicit operator MyInt(int v)
        {
            return new MyInt() { val = v };
        }
        public static implicit operator bool(MyInt t)
        {
            return t.val != 0;
        }
    }
}

结果为真

关于c# - 为什么 C# 中的 1 && 2 是假的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5203770/

相关文章:

java - 对 boolean 结果的误解

java - 自定义或者Java中的操作

c# - C#套接字编程错误

ios - 从 Objective-C 中的 ColdFusion boolean 返回类型获取 BOOL 的更好方法?

c# - 在 .net 中使用 AOP 登录

objective-c - 如何在 objective-c 中设置 boolean 值

javascript - 更改 boolean 值 (Jquery/Javascript)

c# - C# 中恼人的强制转换

c# - 来自 XElement 的内文?

c# - 什么是实现对象池的好方法?