为什么我们可以将字符串添加到组合框c#?

为什么我们可以将字符串添加到组合框c#?,c#,string,combobox,C#,String,Combobox,combobox.Items.Add(objectitem),那么为什么我们可以使用combobox.Items.Add(“一些文本”),虽然“一些文本”是字符串,而不是对象?Astring是引用类型,所以它是对象。combobox所做的就是调用它接收的对象的.ToString()方法,将其转换为字符串(以显示它)。字符串的ToString()只返回字符串 为什么要这样做Add() 让我们看一个使用WinForms的示例: // A simple Person class, Name + Sur

combobox.Items.Add(objectitem)
,那么为什么我们可以使用
combobox.Items.Add(“一些文本”)
,虽然“一些文本”是字符串,而不是对象?

A
string
是引用类型,所以它是
对象。combobox所做的就是调用它接收的对象的
.ToString()
方法,将其转换为字符串(以显示它)。字符串的
ToString()
只返回字符串

为什么要这样做
Add()

让我们看一个使用WinForms的示例:

// A simple Person class, Name + Surname
public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }

    public override string ToString()
    {
        return Name + " " + Surname;
    }
}

// cb is your ComboBox

// Three persons in the ComboBox
cb.Items.Add(new Person { Name = "Bill", Surname = "Gates" });
cb.Items.Add(new Person { Name = "Larry", Surname = "Ellison" });
cb.Items.Add(new Person { Name = "Peter", Surname = "Norton" });

// and then somewhere the user selects an item in the combobox
// and then we can

Person selectedPerson = (Person)cb.SelectedItem;
string selectedPersonDescription = cb.SelectedText;
您不仅可以检索所选项目的描述,还可以检索“整个”所选项目!你看到优势了吗?(如前所述,ComboBox类使用
ToString()
方法自动计算项目的“描述”)


因此,很明显,组合框保存了您
添加(…)
的“整个”对象,并计算了描述(使用
ToString()
)以显示给用户。

多亏了多态性。因为
string
派生自
object
,所以您可以将其传递给该方法,以及从
object
派生的任何其他类型实例(这几乎是所有内容)。

@d准确地说,指针和托管引用不是对象。