所以我創建了一個帶有物件和建構式的汽車類,我正在嘗試獲取這些值,但我收到一個錯誤訊息:沒有給出與所需形式引數對應的引數 c# 這是我的類:
public class Car
{
private int yearOfProduction;
private int engineVolume;
public Car(int yearOfProduction, int engineVolume)
{
this.yearOfProduction = yearOfProduction;
this.engineVolume = engineVolume;
}
public int YearOfProduction { get; set; }
public int EngineVolume { get; set; }
}
}
而我的主要方法:
using System;
namespace Car2
{
class Program
{
static void Main()
{
Car car = new Car();
Console.Write("Year of production: ");
car.YearOfProduction = int.Parse(Console.ReadLine());
Console.Write("Engine volume: ");
car.EngineVolume = int.Parse(Console.ReadLine());
Console.WriteLine(YearOfProduction);
Console.WriteLine(EngineVolume);
}
}
}
uj5u.com熱心網友回復:
您在這里遇到了一些不同的問題。
從Car班級開始:
您只有一個建構式,沒有可以使用的默認建構式new Car()。將您的課程調整為如下所示:
public class Car
{
private int yearOfProduction;
private int engineVolume;
public Car(int yearOfProduction, int engineVolume)
{
this.yearOfProduction = yearOfProduction;
this.engineVolume = engineVolume;
}
public Car() //this is what will be called on new Car()
{
}
public int YearOfProduction { get; set; }
public int EngineVolume { get; set; }
}
否則,您可以通過呼叫您提供的建構式來使類保持原樣,這需要兩個ints,例如Car car = new Car(5, 5).
在您的Main, 行
Console.WriteLine(YearOfProduction);
Console.WriteLine(EngineVolume);
不是指 的屬性car。您需要將其調整為:
Console.WriteLine(car.YearOfProduction);
Console.WriteLine(car.EngineVolume);
uj5u.com熱心網友回復:
您指定該類需要兩個引數才能創建:yearOfProductionand engineVolume,兩者都沒有默認值,因此都是必需的。
public Car(int yearOfProduction, int engineVolume)
{
this.yearOfProduction = yearOfProduction;
this.engineVolume = engineVolume;
}
但是您在沒有引數的情況下初始化實體:
Car car = new Car();
為了代碼的完整性,請洗掉初始化或設定默認值:
public Car(int yearOfProduction = 0, int engineVolume = 0)
{
this.yearOfProduction = yearOfProduction;
this.engineVolume = engineVolume;
}
或者用值初始化:
Car car = new Car(0,0);
uj5u.com熱心網友回復:
您Car撰寫的唯一建構式是:
public Car(int yearOfProduction, int engineVolume)
這意味著Car如果你給它yearOfProduction和 ,你只能創建一個實體engineVolume。像這樣的東西:
int year = 1994;
int volume = 2400;
Car car = new Car(year,volume);
或者,您可以提供第二個建構式:
public Car()
{
YearOfProduction = 1994;
EngineVolume = 2400;
}
順便說一句,當您說“帶有物件的汽車類”時,我認為您的意思是“具有某些欄位和屬性的汽車類”。此外,您的欄位沒有做任何事情,似乎是多余的。
uj5u.com熱心網友回復:
問題是您的建構式需要兩個值
public Car(int yearOfProduction, int engineVolume)
然后你用 none 實體化這個類:
Car car = new Car();
鑒于您實體化類的方式,您應該添加(或替換,取決于您的用例)以下建構式:
public Car()
{
//some stuff
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363431.html
