c# - "Primary constructor body not allowed"是什么意思?

标签 c#

我正在尝试在终端中编译并运行此 C# 程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public class largestNumber
{
    public static void Main(string[] args);
    {
        int UserNumber1 = int.Parse(Console.ReadLine("Enter a number:"));
        int UserNumber2 = int.Parse(Console.ReadLine("Enter a second number:"));
        int UserNumber3 = int.Parse(Console.ReadLine("Enter a third number:"));

        Console.WriteLine("Your numbers were, " + UserNumber1 + ", " + UserNumber2 + ", and " + UserNumber3);
    }
}

但是,当我这样做时,出现此错误:

Number.cs(11,2): error CS9010: Primary constructor body is not allowed

有人可以解释一下这个错误指的是什么吗?

最佳答案

您的应用存在多个问题:

  • 方法实现末尾不带 ;

  • Console.ReadLine 不接受任何参数。它的唯一目的是读取控制台,因此您应该使用 Console.WriteLine 来询问“输入数字”等问题。

  • 您应该将类​​包装在命名空间中(通常命名为您的 .csproj 项目)

请遵循 C# 约定,类名采用 PascalCase,变量采用 CamelCase。当您共享代码时,其他开发人员可以更轻松地阅读和理解它。

所以它应该看起来像这样:

using System;

namespace MyApp
{
    public class LargestNumber
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter a number:");
            int userNumber1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter a second number:");
            int userNumber2 = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter a third number:");
            int userNumber3 = int.Parse(Console.ReadLine());

            Console.WriteLine("Your numbers were, " + userNumber1 + ", " + userNumber2 + ", and " + userNumber3);
        }
    }
}

请注意,我删除了一些无用的 using 语句。

您还应该将文件 Number.cs 重命名为 LargestNumber.cs,您通常希望文件与您的类具有相同的名称。


此外,即使通过复制粘贴您的代码,我也没有遇到与您相同的编译错误。

在 VS2015 下,我有“非抽象和非外部方法必须声明主体”(由额外的分号引起)和“方法 ReadLine 有 0 个参数,但使用 1 个参数调用” 。您收到的错误可能是由代码中其他地方的语法错误引起的。

关于c# - "Primary constructor body not allowed"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31757953/

相关文章:

c# - 异步 CTP : Creating a class that is IAwaitable

c# - 是否可以使用 Obsolete 属性标记 .net 函数

c# - 在空闲事件上重复播放视频,并在检测到用户事件时恢复到上一个​​窗口

c# - 排除通用约束中的类型(可能?)

c# - 将查询字符串字典(或关联数组)转换为字典

c# - 从对象方法中调用管理器/服务类好吗?

c# - 更改参数名称 Web Api 模型绑定(bind)

c# - 通过 jQuery 从发布请求的部分 View 中检索数据

c# - 像实时新闻提要ajax刷新一样实现facebook?

c# - 免费音频播放器API