类的实例不存在?

3

我正尝试让一个单独的类中的方法为我执行一些数学计算,并将结果写入控制台。现在我面临的问题是它显示对象引用没有可用的实例。我之前认为我已经在调用所有其他方法的类中实例化了它,但显然有些地方不对,我不知道该怎么做才能使其正常工作。第二部分的数学计算也会给我同样的错误,但如果我能解决这个问题,我应该能够轻松地解决第二个问题。

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();会创建所需的实例,但显然并不是这样?
4个回答

3
MakeFruits方法中,你声明了两个变量,它们是局部变量,因此EatFruits()无法访问它们。
注意this.:
public void MakeFruits()
{
    this.apple = new Apple(); // "this." is written to make it clearer. 
    this.apple.apple(1.5);    // let's not skip the steps
    this.banana = new Banana();
    this.banana.banana(3.5);
}

因为你在MakeFruits()方法中本地声明了水果,所以类属性applebanana保持为null
在另一种情况下,你的apple()方法没有正确注册半径。应该写成以下形式:
public void SetRadius (double radius)
{
    Radius = radius; // by Alexei
}

如果您仍然不确定,可以查看Mauris在Pastebin上的速成笔记来获取帮助。


我已经做出了更改,但现在它告诉我:“'Apple”:成员名称不能与其封闭类型相同”,在apple类中.... >_> 我感觉像个彻头彻尾的新手。 - user1787114
1
你不能有一个与类名相同的方法。 - Andy
1
@mauris,您说得非常正确-在Radius=Radius中确实没有SO... (而且我知道我当时在想什么-Radius {get;set{Raduis=value;}}-为什么...我猜我需要更多的咖啡...) - Alexei Levenkov
这里,给你咖啡。递上 :coffee: 我刚喝完我的。 - mauris
已经修复了。现在我只需要弄清楚如何让eat方法的输出写入。显然,“public double Eat(double dblpercent){return(PercentFruitLeft-dblpercent);}”并没有实际将值写入命令提示符。 - user1787114
显示剩余5条评论

2

通过使用

Apple apple = new Apple();

你已经将这个版本的苹果限定在MakeFruits方法中。因此,在你的EatFruits方法中,当你访问该作用域可用的苹果版本时,它是一个未初始化的Apple apple。当你尝试访问成员时,会出现错误,因为它还没有被初始化。
我看到的主要问题是作用域和一些大小写使用不当。
class Apple : Fruit
{
 public double Radius { get;set;}

 //public void apple(double radius)//Constructors need to share the same case 
                                 //as their parent and inherently have no return value
 public Apple(double radius)
 {
    //Radius = Radius;//This is a self reference
    Radius = radius;//This will reference the local variable to Apple, Radius
 }
}

主程序中出现了相同的问题

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();//You have already declared apple in this scope
    //apple.apple(1.5);//This is redundant, what you most likely want is to have this done in a constructor
    apple = new Apple(1.5);//this accesses the scoped apple, and uses the Apple constructor
    //Banana banana = new Banana();//same scopeing issue as apple
    banana = new Banana();
    banana.banana(3.5);//the banana class was not shown so I will leave this
 }
 public void EatFruits()
 {
    double dblpercent;
    MakeFruits();//now made properly with scope
    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);//Eat was never shown
    Console.Write("% of your apple, and ");
    banana.Eat(dblpercent);//Eat was never shown
    Console.Write("% of your banana left.");
    Console.ReadLine();
 }
}

0

你只需要知道在你的类中使用时上下文之间的区别:

public void MakeFruits()
{
    Apple apple = new Apple();
    apple.apple(1.5);
    Banana banana = new Banana();
    banana.banana(3.5);
}

你正在告诉编译器,“apple”和“banana”是局部变量,......这些变量仅属于方法“MakeFruits()”,你需要做的是使用关键词“this”,编译器将知道你需要在类定义中实例化变量。

public void MakeFruits()
{
    this.apple = new Apple();
    apple.apple(1.5);
    this.banana = new Banana();
    banana.banana(3.5);
}

0
首先,您需要修复Apple构造函数。
class Apple : Fruit
{
    public double Radius { get;set;}

    public Apple(double radius)
    {
        Radius = radius;
    }

}

上面的代码展示了创建对象的正确方式。

你可能想要尝试这样做:

class Program
{

    private static FruitGarden myGarden;

    static void Main(string[] args)
    {
        //get a new garden

        myGarden = new FruitGarden();
        Console.WriteLine(myGarden.PlantFruit("banana")); 
        //returns "You grew one banana!"
        Console.WriteLine(myGarden.PlantFruit("apple")); 
        //returns "You grew one apple!"
        Console.WriteLine(myGarden.PlantFruit("orange")); 
        //returns "You can't grow that type of fruit!"

        EatFruits();
    }

    static void EatFruits()
    {
        //Now, let's just iterate through our fruit garden and eat all of that 
        //yummy fruit!
        for (int i = 0; i < myGarden.Fruits.Count; i++)
        {
            Fruit myFruitSnack = myGarden.Fruits[i];
            while (myFruitSnack.FruitSize > 0)
            {
                Console.WriteLine(myFruitSnack.TakeBite());
            }
        }

        Console.ReadLine();
    }

}

//We could make this virtual or an interface, but I'll leave that out for now.
public class Fruit
{

    private int fruitSize;

    public int FruitSize
    {
        get
        {
            return this.fruitSize;
        }
    }

    public Fruit(int size)
    {
        this.fruitSize = size;
    }

    //The size of the fruit is an internal property. You can see how 
    //big it is, of course, but you can't magically make a fruit smaller
    //or larger unless you interact with it in a way that is allowable
    //according to the current known laws of the universe and agriculture. 
    //I.E, you can take a bite :)
    public string TakeBite()
    {
        if (this.fruitSize > 0)
        {
            this.fruitSize -= 1; //or any other value you decide to use
        }

        if (this.fruitSize > 0)
        {
            //again, there is so much more you can do here.
            return "You take a bite of the fruit!"; 
        }
        else
        {
            return "You take one more big bite and eat all of the fruit!";
        }

    }

}

public class Apple : Fruit
{
    //Someday, you might want to overload these...
    public Apple(int fruitSize)
        : base(fruitSize)
    {

    }
}

public class Banana : Fruit
{
    //Someday, you might want to overload these...
    public Banana(int fruitSize)
        : base(fruitSize)
    {

    }
}

class FruitGarden
{

    //Public property of FruitGarden that contains all of the fruits it has "grown."
    public List<Fruit> Fruits { get; set; }

    public FruitGarden()
    {
        //Instantiate your list now.
        this.Fruits = new List<Fruit>();
    }

    //There are better ways to do this, but for the sake of your project we're
    //going to do something simple. We'll pass in a string representing the 
    //fruit type.
    public string PlantFruit(string fruitType)
    {
        //We're going to implement a simple factory here. Google 'factory pattern'
        //later and be prepared to spend a lot of time reading over the ideas
        //you're going to run into.
        switch (fruitType.ToLower())
        {
            case "apple":
                this.Fruits.Add(new Apple(10));
                break;
            case "banana":
                this.Fruits.Add(new Banana(5));
                break;
            default:
                return "You can't grow that type of fruit!";
        }

        return "You grew one " + fruitType + "!";
    }

}

现在请记住,这只是一个例子,并忽略了许多非常重要的概念。祝编码愉快!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接