【问题标题】:System.Reflection Get property as an object and set another property of the propertySystem.Reflection 获取属性作为对象并设置该属性的另一个属性
【发布时间】:2021-01-19 09:30:01
【问题描述】:

所以,在我的项目中,在一个 STL 文件上,有一些点,当我移动一个点时,坐标信息会发生变化。当一个点移动时,它必须被标记为已修改。

当我移动点时,我有点的属性名称。从属性名称中,我可以访问该属性,它返回一个 Custom3DPoint。

Custom3DPoint 类有一个 Status 属性。

为了更清楚地解释,我有一个名为 A 的类,它有两个属性 P1 和 P2。我还有另一个名为 B 的类,它具有 A 类型的属性。

如何从propertyname P1中获取对象B的属性并设置P2的值。

这是我尝试过的:

class A
{
    public string P1{ get; set; }
    public string P2 { get; set; }

    public A()
    {
        P1 = "value1";
        P2 = "value2";
    }
}

class B
{
    public A PropA { get; set; }
    public B()
    {
        PropA = new test.A();

    }
}

void Moved(B obj, string propertyName)
{
    var prop = obj.GetType().GetProperty(propertyName);
    var statusProp = prop.GetType().GetProperty("Status"); //this line returns null because

    prop.GetType().GetProperties(); // doesn't return properties of A object.

    statusProp.SetValue(prop, "modified");
}

是否可以使用反射?

【问题讨论】:

  • 看起来你有点困惑,只是在尝试一些随机的东西。 obj.GetType() 获取 B 的类型。 obj.GetType().GetProperty(propertyName) 获取该属性的 PropertyInfoprop.GetType() 获取 PropertyInfo 的类型,而 GetProperty("Status") 调用尝试查找不存在的 PropertyInfo.Status 属性。
  • 也许你在prop.PropertyType.GetProperty(...)之后?
  • 是的,我通过编码我发布的部分看到了这一点。我的问题是,是否有办法根据我从名称中收到的属性设置对象的 Status 属性。如果没有,我将不得不做一个swich case等。
  • 我只是在尝试 PropertyType.GetPrperty,谢谢。我会告诉你它是否有效。

标签: c# reflection


【解决方案1】:

您需要获取属性的值,然后更改内部属性:

void Moved(B obj, string propertyName)
{
    // get property of B object
    var prop = obj.GetType().GetProperty("PropA");
    // get value of B.PropA
    var aValue = prop.GetValue(obj);
    // get property of A object
    var aProp = aValue.GetType().GetProperty(propertyName);
    // change property in A object
    aProp.SetValue(aValue, "modified");
}

【讨论】:

  • 正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-10-22
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
相关资源
最近更新 更多