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

时间:2009-09-09 22:30:36

标签: asp.net reflection c#-3.0

我有两节课。

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

public class Class2 {
   public Class1 myClass1Object {get;set;}
}

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

Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";

有没有办法在使用反射访问属性“myClass1Object.value”时执行上述操作?

提前致谢。

3 个答案:

答案 0 :(得分:11)

基本上将它分成两个属性访问。首先,获取 myClass1Object属性,然后在结果上设置 value属性。

显然,您需要采取任何您拥有属性名称的格式并将其拆分 - 例如按点。例如,这应该具有任意深度的属性:

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

不可否认,您可能需要更多错误检查:)

答案 1 :(得分:1)

我正在寻找获取属性值的情况的答案,当给出属性名称时,但是属性的嵌套级别是未知的。

EG。如果输入是“值”而不是提供完全限定的属性名称,如“myClass1Object.value”。

您的回答激发了我的递归解决方案:

public static object GetPropertyValue(object source, string property)
{
    PropertyInfo prop = source.GetType().GetProperty(property);
    if(prop == null)
    {
      foreach(PropertyInfo propertyMember in source.GetType().GetProperties())
      { 
         object newSource = propertyMember.GetValue(source, null);
         return GetPropertyValue(newSource, property);
      }
    }
    else
    {
       return prop.GetValue(source,null);
    }
    return null;
}

答案 2 :(得分:0)

   public static object GetNestedPropertyValue(object source, string property)
    {
        PropertyInfo prop = null;
        string[] props = property.Split('.');

        for (int i = 0; i < props.Length; i++)
        {
            prop = source.GetType().GetProperty(props[i]);
            source = prop.GetValue(source, null);
        }
        return source;
    }
相关问题