就我個人而言,我不同意這裏的大多數其他海報。我認爲反射的使用應限於真正需要的情況(對象檢查,某些GUI情況等)。在這種情況下,只需多打一點,就可以編寫一個強類型的程序,並且仍然可以做你想做的事。我會提供兩種選擇。這兩種替代方法都可以通過名稱和索引訪問您的屬性。
在第一個替代方案中,我假設我們可以更改屬性的定義。在第二種選擇中,我會假定這些定義必須保持不變。
第一替代移動數據到一個單獨的陣列中,添加了輔助方法通過索引來訪問數據,並改變屬性以使用輔助方法:
private class Version1 {
private readonly string[] underlyingData=new string[50];
public string Foo1 { get { return ReadFoo(1); } set { SetFoo(1, value); } }
public string Foo2 { get { return ReadFoo(2); } set { SetFoo(2, value); } }
public string Foo3 { get { return ReadFoo(3); } set { SetFoo(3, value); } }
//......
public string Foo50 { get { return ReadFoo(50); } set { SetFoo(50, value); } }
private string ReadFoo(int index) {
return underlyingData[index-1]; //1-based indexing
}
private void SetFoo(int index, string value) {
underlyingData[index-1]=value; //1-based indexing
}
}
第二種選擇離開屬性定義不變,以及代表這些屬性的讀寫功能的兩個靜態代表數組。
private class Version2 {
private static readonly Func<Version2, string>[] readers=new Func<Version2, string>[] {
c => c.Foo1,
c => c.Foo2,
c => c.Foo3,
//......
c => c.Foo50,
};
private static readonly Action<Version2, string>[] writers=new Action<Version2, string>[] {
(c,v) => c.Foo1=v,
(c,v) => c.Foo2=v,
(c,v) => c.Foo3=v,
//......
(c,v) => c.Foo50=v,
};
public string Foo1 { set; get; }
public string Foo2 { set; get; }
public string Foo3 { set; get; }
//......
public string Foo50 { set; get; }
private string ReadFoo(int index) {
return readers[index-1](this); //1-based indexing
}
private void SetFoo(int index, string value) {
writers[index-1](this, value); //1-based indexing
}
}
是否有這樣的類設計的原因? – Stefan
它已經這樣設計了。不能改變它。 – DarthVader
如果用反射而不是重構爲更好的設計,你可能會遇到更多麻煩......(添加反射後,很難重構/重新設計它) –