4

次のようなクラスがあるとしましょう。

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

そして、データベースでデータディップを実行しています:

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

現在、次のようにデータをクラスに保存しています。

// 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();
}

これはほんの一例です。実際には、取得する列がもっとあります。列のデータ ディップごとに 1 行を記述するのではなく、コードを小さくして、インデックスを介してループさせたいと思います。インデックスを介して列を取得できるため、これはリーダー オブジェクトを使用して可能です。

しかし、同じ方法でクラスメンバー変数にインデックスを付けることは可能ですか? これは、私が求めていることをよりよく説明するために、書き直された while ループです。

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

この方法でクラス メンバ変数を操作することは可能ですか? または、配列型のメンバー変数を作成する必要がありますか? Person クラスの各メンバー変数を書き出したほうが見栄えがよく、読みやすいので、書き出すことをお勧めします。

事前にどうもありがとうございました。

4

1 に答える 1

6

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.

于 2013-01-30T20:22:36.033 に答える