使用反射设置对象属性的属性

bug*_*ixr 5 asp.net reflection c#-3.0

我有两节课.

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我有一个Class2类型的对象.我需要在Class2上使用反射来设置value属性...即,如果我在没有反射的情况下这样做,这就是我要去做的事情:

Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";
Run Code Online (Sandbox Code Playgroud)

有没有办法完成上述操作,同时使用反射访问属性"myClass1Object.value"?

提前致谢.

Jon*_*eet 11

基本上将它分成两个属性访问.首先,你得到myClass1Object财产,那么你设置value上result属性.

显然,你需要采取你拥有属性名称的任何格式并将其拆分 - 例如通过点.例如,这应该执行任意深度的属性:

public void SetProperty(object source, string property, object target)
{
    string[] bits = property.Split('.');
    for (int i=0; i < bits.Length - 1; i++)
    {
         PropertyInfo prop = source.GetType().GetProperty(bits[i]);
         source = prop.GetValue(source, null);
    }
    PropertyInfo propertyToSet = source.GetType()
                                       .GetProperty(bits[bits.Length-1]);
    propertyToSet.SetValue(source, target, null);
}
Run Code Online (Sandbox Code Playgroud)

不可否认,你可能想要比那些更多的错误检查:)