简体   繁体   English

是否可以使用变量作为类成员的标识符

[英]is it possible to use a variable as identifier of a class member

I am working on a windows forms project and i have a Person Class like this (simplified):我正在处理一个 windows 窗体项目,我有一个这样的 Person 类(简化):

    class Person
    { public string name;
      public int age;

         public Person(string nameInput,int ageInput)
         {
            name=nameInput;
            age = ageInput;
         }
     }

now i wanna initiate some members of the class but i wanna use an Input as the Identifier of the member like this:现在我想启动类的一些成员,但我想使用输入作为成员的标识符,如下所示:

Person someTextBox.Text = new Person(name.Text,age.Text);

Because i cant know how many Persons the user wants to make and i cant know how he wants to call them i cant just do somethink like因为我不知道用户想要创建多少人,我不知道他想如何称呼他们我不能做一些像

Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
...

the identifier is important cause i wanna make a dropdown where the user can select his declared Persons and get the information like age shown标识符很重要,因为我想创建一个下拉列表,用户可以在其中选择他声明的人员并获取显示的年龄等信息

Problem is it doesn´t recognize "someTextBox.Text" as a variable but a string问题是它不能将“someTextBox.Text”识别为变量而是字符串

By overriding the ToString() on the Person class you can return a specific attribute about the Person in question such as full name:通过覆盖Person类上的ToString() ,您可以返回有关相关Person的特定属性,例如全名:

public override string ToString()
{
    return $"{First} {Last}";
}

So when one sets the DataSource of the ComboBox it uses ToString , since we didn't directly specify a DisplayMember to use as the viewable strings in the drop down .因此,当设置ComboBoxDataSource时,它使用ToString因为我们没有直接指定DisplayMember用作下拉列表中的可见字符串

Here I am loading a ComboBox :在这里我正在加载一个ComboBox

public List<Person> People { get; set; }

private void Form1_Load(object sender, EventArgs e)
{
    People = new List<Person>()
    {
        new Person() {First = "Frank", Last = "Wright"},
        new Person() {First = "Omega", Last = "Man"}
    };

    cbPeople.DataSource = people;
}

So when I launch the page I see this:所以当我启动页面时,我看到:

在此处输入图片说明


Here is my full Person class这是我完整的Person课程

public class Person
{
    public string First { get; set; }
    public string Last { get; set; }

    public override string ToString()
    {
        return $"{First} {Last}";
    }

}

How to Retrieve Selected如何检索选定的

Note to be clear on what the ComboBox has as the user selected item, it stores a reference to the People item and returns it in SelectedItem or via a number in SelectedIndex .注意事项是什么明确的ComboBox具有与用户选择的项目,它存储的参考People项目,并返回它SelectedItem或通过一些SelectedIndex So if I wanted the current selected item in the last example I would do this:因此,如果我想要上一个示例中当前选定的项目,我会这样做:

var mySelectedPerson = cbPeople.SelectedItem;

var name = mySelectedPerson.ToString(); // "Frank Wright" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM