我目前正在学习使用abstract
类和virtual
. 我创建了一个简单的表格,可以生成动物的名称、颜色和它们发出的声音。除了颜色显示属性外,一切似乎都正常。结果显示在多行文本框中。有没有办法只用颜色名称而不是这种格式来显示结果Color [DarkGray]
?
单击按钮时的结果:
Betty is a Color [DarkGray] horse with four legs and runs very fast that goes neigh! neigh!!
期望的结果:
Betty is a Dark Gray horse with four legs and runs very fast that goes neigh! neigh!!
代码
namespace farm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public abstract class Animal
{
protected string the_name;
protected string the_type;
protected Color the_color;
protected string features;
public virtual string speaks()
{
return "";
}
public override string ToString()
{
string s = the_name + " is a " + the_color + " " + the_type + " with " + features + " that goes " + speaks();
return s;
}
}
public class Horse : Animal
{
public Horse(string new_name, Color new_color)
{
the_name = new_name;
the_color = new_color;
the_type = "horse";
features = "four legs and runs very fast";
}
public override string speaks()
{
return "neigh! neigh!!";
}
}
private void button1_Click(object sender, EventArgs e)
{
Horse horse1 = new Horse("Topaz", Color.DarkGray);
textBox1.AppendText(horse1.ToString());
}
}
}