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
。约定是 0
为 false
,!= 0
为 true
。 if
语句以完全相同的方式处理条件表达式结果。
在 C++
中引入了 bool
。但它兼容旧规则,0
被当作false
,false
被当作0
,并且有隐式转换在 int
和 bool
之间。
在 C# 中情况不同:有 bool
和 int
并且它们不能相互转换。这就是 C# 标准所说的。期间。
因此,当您尝试重新实现 bool
和 int
兼容性时,您犯了一个错误。您使用 && 这是逻辑运算符,但在 C# 中您不能覆盖它,只能覆盖按位实现的 &。 1 & 2 == 0 == false
!在这里!
您甚至不应该重载按位运算符,为了保持兼容性,您只需保留 operator true
和 false
。
此代码如您所愿:
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/