简体   繁体   中英

Is it possible to reference class member variables using an index in C#?

Let's say I have a class like this:

class Person
{
    public string name;
    public string address;
    public string city;
    public string state;
    public string zip;
}

And I'm performing a data dip on a database:

Select Name, Address, City, State, Zip
FROM Persons_Tbl

Currently, I am storing the data in the class like this:

// Person class and SqlDataReader have been instantiated.

while (reader.Read())
{
    p.name = reader[0].ToString();
    p.address = reader[1].ToString();
    p.city = reader[2].ToString();
    p.state = reader[3].ToString();
    p.zip = reader[4].ToString();
}

This is just an example. In reality, I have more columns to retrieve. Rather than writing one line for each column data dip, I'd like to make the code smaller and loop, via an index. This is possible using the reader object, since I can retrieve columns via an index.

However, is it possible to index class member variables in the same manner? Here is the rewritten while loop, to better explain what I am asking:

// pseudocode!
while (reader.Read())
{
    for (int index = 0; index < 5; index++)
    {
        index of p member variables (i.e. name, address) = reader[index].ToString();   
    }
}

Is it possible to manipulate class member variables in this manner? Or, must I create a member variable that is an array type? I'd prefer to write out each member variable of the Person class, since it looks cleaner and is easier to read.

Thank you very much, in advance.

Yes, you can do something like that.

Example:

class Person
{
    public string name;
    public string address;
    public string city;
    public string state;
    public string zip;

    public string this[int index] { //SPECIAL PROPERTY INDEXERS
        get {
           if(index == 0)
              return name;
           else if(index == 1)
              return address;
           ...
        }
        set {
           if(index == 0)
              name = value;
           else if(index == 1)
              address = value;
           ...
        }
    }
}

What you use here is called Indexers in C# .

after can use it like:

Person person = new Person();
person[0] = "James Bond"; //SET NAME
person[1] = "London";     //SET ADDRESS
.....

Even considering this, may be, original way to resolve this problem, I would first think about possible ways re-architecting the code to avoid this type of solutions.

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