簡體   English   中英

在C#中按字符串獲取對象屬性的屬性

[英]Get property of object property by string in C#

如何使用字符串訪問對象實例中屬性的屬性? 我想自動化將在表單中進行的更改,例如響應以下對象:

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

形式有例如三個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;
}

您可以使用反射樹或表達式樹來執行此操作。

簡單的反射方式(不是很快,但是用途廣泛):

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

注意:如果Vector3是一個結構,則可能無法獲得預期的結果(但這與結構和裝箱有關,而與代碼本身無關)。

為了補充先前的答案,這實際上是您要查找的內容:

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屬性來指定NumericUpDown實例綁定到Vector3對象的哪個屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM