2012-09-07 63 views
0

如何使用字符串訪問對象實例中屬性的屬性? 我想自動化例如響應以下對象更改我將在形式製造:在C中通過字符串獲取對象屬性的屬性#

class myObject{ 
    Vector3 position; 
    public myObject(){ 
     this.position = new Vector3(1d,2d,3d); 
    } 
}; 

形式具有例如3 numericUpDown分別稱爲position_Xposition_Yposition_Z; 而是有三個回調事件:

private void positionX_ValueChanged(object sender, EventArgs e) 
    { 
    // this.model return myObject 
    this.model().position.X = (double) ((NumericUpDown)sender).Value; 

    } 

我會有一個回調,可自動從控制名稱/標籤

下面設置特定屬性的模型是JavaScript的,描述的目的,我想:)

position_Changed(sender){ 
    var prop = sender.Tag.split('_'); ; // sender.Tag = 'position_X';  
    this.model[ prop[0] ] [ prop[1] ] = sender.Value; 
} 
+0

如果你正在做很多這個,你可能想看看FastMember –

回答

3

您可以使用反射或表達式樹來做到這一點。

簡單的反射方式(不是非常快,但通用的):

object model = this.model(); 
object position = model.GetType().GetProperty("position").GetValue(model); 
position.GetType().GetProperty("X").SetValue(position, ((NumericUpDown)sender).Value); 

注:如果Vector3是一個結構,你可能不會得到預期的效果(但與結構和拳擊做,而不是與代碼本身)。

0

爲了補充以前的答案,基本上是你在找什麼:

object model = this.model(); 
object position = model.GetType().GetProperty("position").GetGetMethod().Invoke(model, null); 
var propName = (string) ((NumericUpDown)sender).Tag; 
position.GetType().GetProperty(propName).GetSetMethod().Invoke(model, new [] {((NumericUpDown)sender).Value}); 

也就是說,你可以只使用的ControlTag屬性來指定到你的Vector3財產對象NumericUpDown實例被「綁定」到。