我想在一個單獨的類中的方法爲我做一些數學,然後將結果寫入控制檯。我現在遇到的問題是,它說對象引用沒有要使用的實例。我以爲我在類中早些時候實例化了調用所有其他方法的方法,但顯然有些東西是不正確的,我不知道該怎麼做才能使它工作。數學的第二部分會給我同樣的錯誤,但是如果我能解決這個問題,我應該能夠輕鬆地修復第二部分。類的實例不存在?
class FruitGarden
{
private Apple apple;
private Banana banana;
static void Main(string[] args)
{
FruitGarden fruitGarden = new FruitGarden();
fruitGarden.EatFruits();
}
public void MakeFruits()
{
Apple apple = new Apple();
apple.apple(1.5);
Banana banana = new Banana();
banana.banana(3.5);
}
public void EatFruits()
{
double dblpercent;
MakeFruits();
Console.WriteLine("You have an Apple and a Banana in your fruit garden.\n");
Console.WriteLine("What Percent of the Apple would you like to eat?");
dblpercent = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("\nWhat Percent of the Banana would you like to eat?");
dblpercent = Convert.ToDouble(Console.ReadLine());
Console.Write("You have ");
apple.Eat(dblpercent);
Console.Write("% of your apple, and ");
banana.Eat(dblpercent);
Console.Write("% of your banana left.");
Console.ReadLine();
}
}
,它試圖引用蘋果類是:
class Apple : Fruit
{
public double Radius { get;set;}
public void apple(double radius)
{
Radius = Radius;
}
}
我認爲蘋果apple = new Apple();
將使其所需的實例,但顯然不是?
我做了改變,但現在它告訴我「'蘋果':成員名稱不能與他們的封閉類型相同」在蘋果類....> _>我覺得自己像一個總的菜鳥 – user1787114
@alexeilevenkov感謝編輯 – Andy
你不能有一個方法,它是類的名字 – Andy