Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 反射将属性作为对象获取,并设置该属性的另一个属性_C#_Reflection - Fatal编程技术网

C# 反射将属性作为对象获取,并设置该属性的另一个属性

C# 反射将属性作为对象获取,并设置该属性的另一个属性,c#,reflection,C#,Reflection,所以,在我的项目中,在STL文件中,有一些点,当我移动一个点时,坐标信息会改变。移动点时,必须将其标记为“已修改” 当我移动点时,我有点的属性名。从属性名称,我可以访问该属性,它返回一个Custom3DPoint Custom3DPoint类具有Status属性 为了更清楚地解释,我有一个名为a的类,它有两个属性P1和P2。我还有另一个名为B的类,它的属性类型是a 如何从propertyname P1获取对象B的属性并设置P2值 以下是我尝试过的: class A { public st

所以,在我的项目中,在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");
}

是否可以使用反射?

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

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");
}

看起来你有点困惑,只是在尝试一些随机的事情
obj.GetType()
获取
B
的类型
obj.GetType().GetProperty(propertyName)
获取该属性的
PropertyInfo
prop.GetType()
获取
PropertyInfo
的类型,以及试图查找
PropertyInfo.Status
属性的
GetProperty(“Status”)
调用,该属性不存在。也许您是在查找
PropertyType.GetProperty(…)
?是的,通过对我发布的部分进行编码,我看到了这一点。我的问题是,是否有一种方法可以根据从名称接收的属性设置对象的Status属性。如果没有,我将不得不制作一个swich case等。我只是在尝试PropertyType.GetPrperty,谢谢。我会告诉你它是否有效。这正是我想要的。谢谢