1

我刚刚接触到 C# 的世界。我现在正在学习如何在 Windows 窗体中使用抽象类和虚拟方法。我有结构/想法,但需要帮助填写我的表单代码。我的基本抽象类名为Plants,四个子类名为Trees、和Tomatoes,一个名为 的虚拟方法和一个在所有方法之外的名为的方法。 SeedsBerriesGet_valueReport

我想button1单击为每个类创建至少两个对象,并使用对另一个类的textBox1调用将它们显示在多行中,以显示每种植物的价值和所有植物的总价值。关于如何解决这个问题的任何想法或帮助?ReporttextBox2

代码

namespace plant_farm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public abstract class Plants
        {
            protected string the_name;
            //may need more strings but not sure

            public virtual string Get_Value()
            {
                return "";

                /*
                   Multiplies the number of items times the value per 
                   item and returns the product as a double.
                */
            }

            public override string ToString()
            {

                return "";

              /* 
                Returns a string that gives all the relevant information 
                for the object(including an indication of wheter it is a 
                tree, seed, etc.
              */


            }
        }

        public class Trees : Plants
        {
            /*
              Includes a variety(oak, cherry, etc.), height in feet,
              the number of trees in stock, and the price of each tree.
            */
        }

        public class Tomatoes : Plants
        {
            /*
              Includes: Type(big boy, early girl, etc.), the size of the 
              tomatoes expected (small, medium, or large), the price of each plat,
              the number of plants per plat (6, 12, 24, etc.) and the number of 
              plats in stock.
            */
        }

        public class Seeds : Plants
        {
            /*
              Includes: Type of seeds(pumpkin, cantaloupe, cucumber, etc.), 
              the number of packets in stock, and the cost per packet.
            */
        }

        public class Berries : Plants
        {
          /*
           Includes: Type of plant(blackberry, strawberry, etc.), the variety
           (AAA early, FrostStar, etc), the month of highest bearing (May, June,
           etc.), the number of plants in stock, and the price per plant.
          */
        }

        public void Report()
        {
            /*
            Is passed a Plant object and a TextBox and adds the ToString result of 
            the object to the textbox and then skips to the next line.
             */
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}
4

1 回答 1

1

你的问题有点含糊。我建议继续阅读更多内容,特别是关于继承和组合之间的区别。继承是“是”关系,而组合是“具有”关系。

树“是”植物,番茄植物“是”植物。浆果“是”种子(不是植物) 植物“有”种子。

这将导致一个结构,其中植物的抽象类将包含一个种子实例,该实例本身是浆果、松果、坚果等的抽象基类......

归根结底,这可能是一个非常糟糕的尝试使用的示例,因为您可能会对继承发疯,这通常是一个坏主意,尤其是对于初学者而言。

而是从理解组合开始,然后通过接口进行多态性,然后继续使用抽象类和虚拟成员进行继承。

于 2012-10-14T22:53:04.287 回答