2013-04-09 53 views
2

可以通過索引訪問屬性嗎?C#類屬性,按索引獲取它們

以類Person爲例,它可能具有屬性「BirthNo」和「Gender」。如果我想訪問BirthNo的價值,是否有可能以任何方式編寫p。[0] .Value還是必須寫person.BirthNo.Value?

Person p = new Person 
//I have this: 
string birthNo = p.BirthNo.Value; 
//I want this: 
string birthNo = p.[0].Value; 
+6

他們**不屬性**,但**屬性**。要通過索引得到它們,你必須在僞代碼中使用** Reflection **:'string birthNo =(string)p.GetType()。GetProperties()[0] .GetValue(p,null);'。 – 2013-04-09 18:06:54

+0

否;你爲什麼想要?我懷疑有一種更好的方法可以做到你想做的事情,而不需要通過索引訪問屬性。 – 2013-04-09 18:09:07

+0

@Adriano你應該把你的評論作爲回答 – Alex 2013-04-09 18:09:09

回答

4

p.[0].Value是不正確的C#代碼,所以你絕對不能寫這個。

你可以嘗試使用indexers,但你必須用你自己寫了很多邏輯的,這樣的:

public T this[int i] 
{ 
    get 
    { 
     switch(i) 
     { 
      case 0: return BirthNo; 
      default: throw new ArgumentException("i"); 
     } 
    } 
} 

和調用代碼看起來是這樣的:

p[0].Value 

但是,這是可怕的事情,你甚至不應該考慮用這種方式!*

+1

+1表示並說這種方法有多可怕。 – 2013-04-09 18:13:07

+0

另外+ 1可怕的。 – IdeaHat 2013-04-09 18:22:46

1

你可以只有一條g在Person類中的字典,並在屬性更改時將字符串值寫入它。事情是這樣的:

class Person 
    { 
     Person() 
     { 
      properties.Add(0, "defaultBirthNo"); 
     } 

     Dictionary<int, string> properties = new Dictionary<int,string>(); 

     private int birthNo; 

     public int BirthNo 
     { 
      get { return birthNo;} 
      set { 
       birthNo = value; 
       properties[0] = birthNo.ToString(); 
      } 
     } 
    } 

當你使用設置屬性

person.BirthNo = 1; 

例如,然後你可以檢索:

string retreivedBrithNo = person.properties[0]; 

這是令人難以置信的凌亂,我做不到想想爲什麼你想這樣做,但無論如何這都是一個答案! :)

+0

如果我是寫班的人,那就足夠了。我不是,我只是用它。在遍歷該對象後,用foreach(Person中的personList) foreach(012)。 foreach(PropertyInfo物品親自物業) {... 我得到即item.name,在我的情況下,BirthNo。我想要這個人birthno的價值,既然p.item.name是不可能使用的,我希望能夠使用索引。 感謝您的答覆:) – 2013-04-09 19:45:58