我刚刚被介绍到C#世界。我现在正在学习如何在Windows窗体中使用抽象类和虚方法。我有结构/想法,但需要帮助填写我的表格代码。我的基本抽象类名为Plants
,四个子类名为Trees
,Tomatoes
,Seeds
和Berries
,一个名为Get_value
的虚拟方法和方法名为Report
的名称不在所有方法之内。
我希望button1
点击为每个类创建至少两个对象,并使用对textBox1
和另一个Report
的调用在多行textBox2
中显示它们显示每种植物的价值和所有植物的总价值。关于我如何能够解决这个问题的任何想法或帮助?
CODE
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)
{
}
}
}
答案 0 :(得分:1)
你的问题有点模糊。我建议继续阅读,特别是继承和组合之间的区别。继承是一个"是一个"组成是"有一个"关系。
Tree"是"植物,番茄植物"是"厂。贝瑞"是一个"种子(不是植物)植物"有"种子。
这将导致一个结构,其中Plant的抽象类将包含一个Seed实例,它本身是浆果,松果,坚果等的抽象基类......
最终这可能是一个非常糟糕的尝试,因为你可以坚持继承,这通常是一个坏主意,特别是对初学者。
从理解组合开始,然后通过接口进行多态,然后继续使用抽象类和虚拟成员进行继承。