0

我目前正在学习使用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());
        }
    }
}
4

2 回答 2

2

是的,在您的 ToString 方法中,使用:

the_color.Name

或者更好的是,如果你想在字符串包含大写字符的地方有一个带有空格的字符串,例如 DarkGray => Dark Gray,你可以定义一个像这样的扩展

public static class ColorExtensions
{
    public static string GetColorString(this Color color)
    {
        StringBuilder sb = new StringBuilder();
        foreach(char c in color.Name.ToCharArray())
        {
            if (char.IsUpper(c))
                sb.Append(' ');

            sb.Append(c);
        }

        return sb.ToString();
    }
}

并这样称呼它

the_color.GetColorString()
于 2012-10-12T13:57:09.317 回答
1

您可以使用Name颜色的属性来获取人类可读的名称。

string s = the_name + " is a " + the_color.Name + " " + the_type + " with " + features + " that goes " + speaks(); 
return s;

通常,在 MSDN 上查找命名空间并查看可用的方法和属性会有所帮助。在这种情况下,您可以查看 MSDN 上的颜色结构,您会在“属性”部分找到Color.Name的属性:

此方法返回用户定义的颜色名称(如果颜色是从名称创建的)或已知颜色的名称。对于自定义颜色,返回 RGB 值。

于 2012-10-12T13:57:22.753 回答