c# - c#程序中的"} expected"错误

标签 c#

我在 C# 中创建了两个类,但是当我为第二个类创建构造函数时,它给了我错误“} expected” 我不明白哪里出了问题,因为有足够多的 {} 集。对于代码底部的最后一个大括号,它也会给出相同的错误。

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

namespace Cars
{
    class Program
    {
        static void Main(string[] args)
        {
            Car c1 = new Car("Audi","A1","AB12 CDE",1985, 15000);
            Console.WriteLine(c1);
            string str = Console.ReadLine();
        }
    }

    class Fleet
    {
        public Fleet()
        {
            public Car[] carArray = new Car[100];
        }
    }

    class Car
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public string Registration { get; set; }
        public int Year { get; set; }
        public int Value { get; set; }

        public Car(string make, string model, string registration, int 
year, int value)
        {
            Make = make;
            Model = model;
            Registration = registration;
            Year = year;
            Value = value;
        }

        public override string ToString()
        {
            return string.Format("Make: {0}\nModel: {1}\nRegistration: {2}\nYear: {3}\nValue: {4:C}", Make, Model, Registration, Year, Value); 
        }
    }
}

最佳答案

在你的类里面

class Fleet
{
    public Fleet()
    {
        public Car[] carArray = new Car[100];
    }
}

您已将 carArray 声明为 public,但它位于构造函数中。方法中不能有修饰符。在方法中声明的任何变量始终只在该方法的范围内可见。我假设您在类中而不是构造函数中需要它,所以只需像这样将其移出...

class Fleet
{
    public Car[] carArray = new Car[100];

    public Fleet()
    {
    }
}

一切都很好。

关于c# - c#程序中的"} expected"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061679/

相关文章:

c# - 如何使用mysql获取数据库中的所有记录?

c# - 从动态创建的复选框中获取错误值

c# - 将人的高度从英尺和英寸转换为英寸 C#

C# ASP.NET MVC 5 如何执行原始查询?

java - 启动一个进程会启动另一个进程,该进程会启动 Java 进程吗?

c# - 处理 Windows Phone 8 silverlight 中的客户端 SSL 证书错误

c# - MVC 'Find' 方法需要很长时间(甚至在发布时)? (使用迷你配置文件)

c# - CNG 从文件导入 ECC 公钥/私钥

c# - 在 C# 中确定图像的颜色十六进制值

c# - 数据库连接导致 CrystalReports ReportDocument 内存泄漏