Kos*_*mos 4 c# combobox overriding tostring
public partial class TestConrol : UserControl
{
public TestConrol()
{
InitializeComponent();
}
public override string ToString()
{
return "asd";
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TestConrol tc1 = new TestConrol();
comboBox1.Items.Add(tc1);
TestConrol tc2 = new TestConrol();
comboBox1.Items.Add(tc2);
}
}
Run Code Online (Sandbox Code Playgroud)
当表单加载时,我看到combobox有两个空名称的项目,而不是"asd":/
但如果我在公共类中重写ToString(),而不是从任何东西派生,这个工作:
public class TestClass
{
public override string ToString()
{
return "bla bla bla";
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TestClass tcl = new TestClass();
comboBox1.Items.Add(tcl);
}
}
Run Code Online (Sandbox Code Playgroud)
之后我在组合框中看到"bla bla bla"