gpt4 book ai didi

c# - 如何在列表框中显示替代对象的表示?

转载 作者:行者123 更新时间:2023-12-02 04:24:28 27 4
gpt4 key购买 nike

不久前,我遇到过一篇文章,其中作者指出,如果我有一个 ListBox ,则其中的对象不必由返回的 string 表示ListBox 内的 ToString() 方法

这怎么可能?

例如我有一个:

 public class Car {
public static int ID { get; set; }
public int Id { get; set; }
public string Make { get; set; }
public int Power { get; set; }


public Car(string Make, int Power) {
Id = ID++;
this.Make = Make;
this.Power = Power;
AddToClassExtension(this);
}


public override string ToString() {
return Id + "." + Make + " " + Power;
}
}

Form中的ListBox lb。我想在 lb 的每一行中仅显示 car.Id,但不更改 ToString() 方法。是否可以?

最佳答案

您可以指定DisplayMember对于 ListBox - 在本例中,您可以将其设置为 "Id",以便控件从显示的每个项目中获取该属性。

这是一个简短但完整的示例(为简洁起见,使用 C# 6):

using System;
using System.Collections.Generic;
using System.Windows.Forms;

public class Car {
// C# 6 finally allows read-only autoprops. Yay!
public int Id { get; }
public string Make { get; set; }

public Car(int id, string make)
{
this.Id = id;
this.Make = make;
}

public override string ToString() {
return Id + "." + Make;
}
}

class Test
{
static void Main()
{
var cars = new List<Car>
{
new Car(10, "Ford"),
new Car(20, "Nissan"),
new Car(45, "Rolls-Royce")
};

var listBox = new ListBox
{
DataSource = cars,
DisplayMember = "Id",
Dock = DockStyle.Fill
};

var form = new Form
{
Controls = { listBox }
};
Application.Run(form);
}
}

对于更复杂的格式设置,您可以在启用格式设置后使用 Format 事件。例如,在上面的示例中,将 listBox 声明更改为:

var listBox = new ListBox
{
DataSource = cars,
Dock = DockStyle.Fill,
FormattingEnabled = true,
};
listBox.Format += (sender, args) =>
{
var car = (Car) args.Value;
args.Value = string.Format("Id: {0}; Make: {1}", car.Id, car.Make);
};

关于c# - 如何在列表框中显示替代对象的表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com