在列表框中显示对象名称

本文关键字:对象 显示 列表 | 更新日期: 2023-09-27 18:34:21

我试图在列表框中显示我的对象名称,但无法以良好的方式显示。我可能会手动声明所有名称,但我想通过将我的对象名称显示为数据源来实现。找不到该怎么做。我想知道我是否应该制作一个列表,或者是否有任何简单的方法可以在列表中显示我的对象名称。可能 foreach 循环可以轻松修复它,但我找不到如何只选择名称并将其添加到列表框中。

我的代码如下所示:

class Platform
{
public string name, action, adventure, rpg, simulation, strategy, casual, audianceY, audianceE, audianceM;
        public Platform(string nameIn, string actionIn, string adventureIn, string rpgIn, string simulationIn, string strategyIn, string casualIn, string audianceYIn, string audianceEIn, string audianceMIn)
        {
            name = nameIn;
            action = actionIn;
            adventure = adventureIn;
            rpg = rpgIn;
            simulation = simulationIn;
            strategy = strategyIn;
            casual = casualIn;
            audianceY = audianceYIn;
            audianceM = audianceMIn;
            audianceE = audianceEIn;
        }
        public override string ToString()
        {
            return name;
        }
}

public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        private void Main_Load_1(object sender, EventArgs e)
        {
            //---------------------------------
            // Platform List
            //---------------------------------
            Platform PC = new Platform("PC", "++", "+++", "++", "+++", "+++", "---", "+", "++", "+++");
            Platform G64 = new Platform("G64", "++", "+++", "++", "++", "+++", "--", "+", "++", "+++");
            Platform TES = new Platform("TES", "+", "--", "+", "+", "--", "+++", "+++", "++", "---");
         }

          foreach (???)
          {
          listBox1.Items.Add(???)
          }
    }

在列表框中显示对象名称

您的代码不会按原样编译,因此我只是假设您打算在 Main_Load 事件中包含 foreach 循环。

如果将所有新的平台实例添加到列表中,而不是将单个变量添加到列表中,则会容易得多。然后,可以将列表设置为数据源,并指定显示/值成员应是什么。

private void Main_Load(Object sender, EventArgs e)
{
    var platforms = new List<Platform> {
        new Platform("PC", "++", "+++", "++", "+++", "+++", "---", "+", "++", "+++"),
        new Platform("G64", "++", "+++", "++", "++", "+++", "--", "+", "++", "+++"),
        new Platform("TES", "+", "--", "+", "+", "--", "+++", "+++", "++", "---")
    };
    listBox1.DataSource = platforms;
    listBox1.DisplayMember = "name";
    listBox1.ValueMember = "name";
}

要绑定到"name",您需要将其更改为属性:(否则您将获得ArgumentException

public string name { get; set; }

几个想法:

  • 如果要重用这些平台,则必须在方法外部声明它们。

  • 创建带有getter/setter的公共属性比像您当前所做的那样的公共字段更典型,并且也将它们大写,如下所示:

    public string Name { get; set; }