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

标签 c# operator-overloading operators

是否可以为 int float ?

例子:

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

最佳答案

在使用整数时,您可以使用按位运算符来实现这一点。

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

看起来像这样:

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

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

编辑: 再考虑一下,我相信你不能这样做。所有非零值都被评估为真,除了零被评估为假。请记住这一点,使用按位和 (&) 对两个非零值进行运算可能会求值为零。例如:a = 1, b = 2 -> a & b = 0。此外,如果应用于 -1,按位取反 (~) 只会计算为零。当转换为 bool 值时,~1 的计算结果为非零。

关于原始类型的 C# 重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919714/

相关文章:

c# - 似乎无法解析 KeyedByTypeCollection?

floating-point - 为什么将整数添加到 float 时会出错?

c++ - 是否可以在 C++ 中声明 operator= private 并同时由编译器合成

C++ 运算符 [] 语法

c# - ASP.NEt MVC 使用 Web API 返回 Razor View

c# - Dispatcher Invoke(...) 与 BeginInvoke(...) 混淆

c# - 如何使用 C# 获取任务栏中固定应用程序的列表

c++ - 重载运算符 - () 作为自由函数而不是成员函数的意义?

c++ - 如何在创建复制构造函数时正确重载 operator=

C++:需要帮助理解运算符重载错误