原始类型的 C# 重载运算符

C# overload operators for primitive types

是否可以为 intfloat 等类型重载 ||&&! 等运算符?

示例:

float a, b; int c;
//instead of this:
return Convert.ToBoolean(a) || Convert.ToBoolean(b) && !Convert.ToBoolean(c);
//do this:
return a || b && !c;

对于 OR 你有 | 符号。例如:

return a | b; 
如果 abtrue

会 return true。否则,它将 return false.

此外,您还可以使用 & 运算符来执行此操作:

return a & b;

这将 return true 如果 ab 其中 true。否则,它将 return false。我建议您查看此处的文档以获取更多运算符:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators

当然,正如网站标题所说(布尔运算符),不是不能对整数和浮点数执行此操作,因为它们没有任何意义。我的意思是你为什么要 return 2 or 4 & 5?它只是没有任何价值。如果你发现了什么,请看这里:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/overloadable-operators

编辑: 这实际上取决于你在做什么,正如你所指出的,它对某些 problems/algorithms 很有用,比如处理矩阵等。但是因为您不一定指定您在做什么,我将其理解为日常编程。无论如何,上面是整数的运算符。不过,我认为您不能用浮点数重载运算符。

此外,@SohaibJundi 说(很棒的工作),而不是 ! 你使用这个:

return ~a;

这将 return 与 a 的值相反。意思是如果 atrue 它会 return false 如果它是 false 它会 return true.

希望对您有所帮助!

  1. 来自 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/introduction#expressions

    Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

  2. 来自 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#operator-overloadability

    A user-defined type cannot overload the conditional logical operators && and ||. However, if a user-defined type overloads the true and false operators and the & or | operator in a certain way, the && or || operation, respectively, can be evaluated for the operands of that type.

了解更多信息https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#user-defined-conditional-logical-operators

您可以使用 bit-wise 运算符在使用整数时实现此目的。

您将使用 & 而不是 &&, |而不是 ||和 ~ 而不是 !.

看起来像这样:

    int a, b, c;
    //instead of this:
    //return Convert.ToBoolean(a) || Convert.ToBoolean(b) && !Convert.ToBoolean(c);
    //do this:
    return (a | b & ~c) != 0;

但是如果是浮点数,则不能使用这些运算符。

编辑: 再考虑一下,我相信你不能这样做。所有非零值都被评估为真,除了零被评估为假。请记住,使用 bit-wise 和 (&) 的 and-ing 两个非零值可能会计算为零。例如:a = 1, b = 2 -> a & b = 0。此外,如果应用于 -1,bit-wise 否定 (~) 只会评估为零。当转换为布尔值时,~1 的计算结果为非零。