简体   繁体   中英

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):

    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

By overriding the ToString() on the Person class you can return a specific attribute about the Person in question such as full name:

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 .

Here I am loading a 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

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 . 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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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