我在 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/