c# - 为什么在 C# 中没有用于 8 位和 16 位整数的算术运算符 (+,-,*,/,%)?

标签 c#

<分区>

知道没有算术运算符 +-*/% 用于 C# 中的 8 位和 16 位整数。我正在阅读第 23 页上的“C# 5.0 Pocket Reference”,如下所示。

enter image description here

以下代码无法编译。

class Program
{
    static void With16Bit()
    {
        short a = 1;
        short b = 2;
        short c = a + b;
        Console.WriteLine(c);
    }

    static void With8Bit()
    {
        byte a = 1;
        byte b = 2;
        byte c = a + b;
        Console.WriteLine(c);
    }

    static void Main(string[] args)
    {
        With8Bit();
        With16Bit();
    }
}

为什么 C# 设计者要这样做?他们对此有何考虑?

最佳答案

Int8Int16的算术;但结果是 int32 所以你必须cast:

class Program
{
    static void With16Bit()
    {
        short a = 1;
        short b = 2;
        short c = (short) (a + b); // <- cast, since short + short = int
        Console.WriteLine(c);
    }

    static void With8Bit()
    {
        byte a = 1;
        byte b = 2;
        byte c = (byte) (a + b); // <- cast, since byte + byte = int
        Console.WriteLine(c);
    }

    static void Main(string[] args)
    {
        With8Bit();
        With16Bit();
    }
}

关于c# - 为什么在 C# 中没有用于 8 位和 16 位整数的算术运算符 (+,-,*,/,%)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22069305/

相关文章:

c# - GetManifestResourceStream() 返回 null

c# - 在界面中调用 c# 事件

c# - 确保方法返回值不被库丢弃

c# - 多个值包含动态 Linq

c# - 后台任务 UWP Windows 10 中的 Websockets

c# - 导入 C# 应用程序的 C++ DLL

c# - 您可以使用 ManagementEventWatcher 类查询什么

c# - 在 Windows 窗体应用程序中 Hook 消息循环?

c# - 获得对 "fall through"面板的点击

c# - 如何使用C#从下面的字符串中提取键