C# 在C中通过字符串获取对象属性的属性#

C# 在C中通过字符串获取对象属性的属性#,c#,C#,如何使用字符串访问对象实例中属性的属性? 我希望自动化我将在表单中进行的更改,例如响应以下对象: class myObject{ Vector3 position; public myObject(){ this.position = new Vector3( 1d,2d,3d); } }; 表单有三个numericUpDown分别调用position\ux,position\uy,position\uz; 而是对事件进行三次回调,如下所示: private v

如何使用字符串访问对象实例中属性的属性? 我希望自动化我将在表单中进行的更改,例如响应以下对象:

class myObject{
   Vector3 position;
   public myObject(){
       this.position = new Vector3( 1d,2d,3d);
   }
};
表单有三个
numericUpDown
分别调用
position\ux
position\uy
position\uz
; 而是对事件进行三次回调,如下所示:

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

  }
我将有一个回调,它可以从控件名/标记自动设置模型中的特定属性

下面是javascript,它描述了我想要的用途:)


您可以使用反射树或表达式树来实现这一点

简单的反射方式(不是很快,但用途广泛):


注意:如果
Vector3
是一个结构,您可能无法获得预期的结果(但这与结构和装箱有关,而不是与代码本身有关)。

您可以使用反射树或表达式树来实现这一点

简单的反射方式(不是很快,但用途广泛):


注意:如果
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});

也就是说,您可以使用
控件的
标记
属性
来指定
NumericUpDown
实例“绑定”到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});

也就是说,您可以使用
控件的
标记
属性
来指定
NumericUpDown
实例“绑定”到Vector3对象的哪个属性。

如果您做了很多这方面的工作,您可能需要查看FastMember如果您做了很多这方面的工作,您可能需要查看FastMember
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});