문제

두 개의 수업이 있습니다.

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

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

Class2 유형의 대상이 있습니다. Class2에 반사를 사용하여 값 속성을 설정해야합니다. 즉, 반사없이 수행 한 경우 이것이 제가 처리하는 방법입니다.

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

"myclass1object.value"속성에 액세스하기 위해 반사를 사용하는 동안 위의 방법이 있습니까?

미리 감사드립니다.

도움이 되었습니까?

해결책

기본적으로 두 개의 속성 액세스로 분할하십시오. 너 먼저 가져 오기 그만큼 myClass1Object 재산, 당신 세트 그만큼 value 결과에 대한 속성.

분명히 당신은 속성 이름을 가진 형식을 가져 와서 DOTS로 나누어야합니다. 예를 들어, 이것은 임의의 속성 깊이를 수행해야합니다.

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

물론 아마도 당신은 아마 그보다 조금 더 오류 검사를 원할 것입니다 :)

다른 팁

재산 이름이 주어질 때 재산 가치를 얻을 수있는 경우에 대한 답을 찾고 있었지만 속성의 중첩 레벨은 알려져 있지 않습니다.

예를 들어. 입력이 "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;
}
   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;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top