【问题标题】:Variables seem to be changing type after they are declared变量在声明后似乎正在改变类型
【发布时间】:2023-03-11 19:45:02
【问题描述】:

我已经为我正在做的一个学习练习编写了这段代码,我正在为我的 Android 手机使用 c# Offline Compiler 应用程序,如果这发生了变化。

每当我尝试运行程序时,都会弹出一个编译错误,告诉我我正在尝试将类型 int 隐式转换为 byte。我已尽我所能检查了所有内容,但我终生无法找到问题,我似乎无法在线找到解决方案或问题。我有一种感觉,这是我还没有学过的简单东西。这是代码……有什么想法吗?

public static class Program
{
    public static void Main()
    {

        for (byte i = 1; i < 255; i++)
        {
            byte mask = 4;
            byte filteredNumber;

            filteredNumber = i & mask;

            if (filteredNumber == 4)
                Console.WriteLine(i);
        }
    }
}

问题似乎发生在filteredNumber = i &amp; mask;这一行附近

【问题讨论】:

    标签: c# casting type-conversion


    【解决方案1】:

    这是因为&amp; 运算符将int 值作为参数并返回int 值。

    尝试使用

    转换结果
    filteredNumber = (byte) (i & mask);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多