c# - 我无法在控制台项目中将引用编号的格式设置为 "byte"或 "short"?

标签 c# console

实际上这是我在这个网站上的第一个问题,我希望这是提出此类问题的正确方式。

我只是在 Youtube 上从头开始学习 C#。

我创建了一个简单的控制台项目,它具有乘法函数,如下所示,但我无法将我的引用编号(编号 1、编号 2)设置为“短”或“字节”。但我可以将它们设置为“long”、“decimal”、“int”等。

我几乎没有搜索,我有理论认为这是关于每个参数的位和字节计数,但不能真正理解这个概念。

任何人都可以用简单的语言解释我遇到的这个错误吗?感谢您的任何解释:)

using System;

namespace HelloWorld
{
class Program
{
    static void Main(string[] args)
    {
        try
        {
            Start:
            int number1;
            int number2;

            Console.Write("enter number to multiply:");
            number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("enter another number:");
            number2 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("the result is:" + number1 * number2 + "(" + number1 + "X" + number2 + ")");
            Console.WriteLine();
            goto Start;
        }
        catch (Exception)
        {
            Console.WriteLine("hey silly! that's not even a number:)");
        }
    }
}

最佳答案

你走在正确的轨道上;它是关于类型的隐式转换和强类型。

不要让你负担太多的细节,你可以做一些调整

短:

注意 ToInt16

short number1;
//etc
number1 = Convert.ToInt16(Console.ReadLine());

字节:

注意:ToByte

byte number1;
//etc
number1 = Convert.ToByte(Console.ReadLine());

left as an exercise


重要的是,尽管所有类型都由位组成,并且基本上都是数字,但 C# 想要确保您的意思是您所说的并强制您使用正确的 type


那么,为什么它适用于 decimal 等?

是因为C#认为它对implicitly convert them有效,因此编译器正在为你做这件事。

在链接中,您可以看到对于 int(又名 Int32),以下隐式转换是预定义的:

//from  |  to
//int   |  long, float, double, or decimal

在链接表中,您还可以看到反过来,从 byteint 是允许的。


重要的教训:C# 是强类型的:如果你说它是 Int16(又名短),你必须只将它用作 Int16(而不是 Int32)

快乐编码;-)

关于c# - 我无法在控制台项目中将引用编号的格式设置为 "byte"或 "short"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448380/

相关文章:

c# - 基本泛型接口(interface)上的扩展方法

c# - F5 后面带有 Redis 背板的 SignalR - StatusCode : 400, ReasonPhrase: 'Bad Request'

c# - 当我使用 Response.Redirect() 或 Server.Transfer() 我的用户被注销

linux - 清理 linux 控制台的任何输出

javascript - 为什么它不会 Console.log 结果?

c# - asp.net注销后历史记录不清晰的问题

c# - 使用 MVC 4 在 C# 中使用 Session 进行 foreach 循环

c# - 在控制台应用程序的文本输出期间对按键使用react

创建简单的显示

linux - 键盘扫描码?