2014-12-18 17 views
1

저는 C#을 처음 사용 했으므로 리플렉션을 사용하여 특정 작업을 수행해야합니다.파생 된 객체를 사용한 리플렉션 사용

이것은 다음과 같습니다. 저는 Base라는 클래스를 파생 한 파생 클래스를가집니다. Base 클래스 내에 Prop 클래스라고하는 속성 인 또 다른 public 클래스가 있습니다. Prop 클래스에는 propString이라는 String 유형의 공용 속성이 있습니다. 파생 클래스와 기본 클래스 모두 동일한 네임 스페이스 아래에 있습니다.

가 첫 번째 클래스 내에서 속성의 "전체 경로"의 문자열을 받아 그 유형을 추출 할 필요가 : 나는 두 가지 기능을 쓸 필요가

namespace mynamespace 

public class Base { 

    public Prop prop { get ; set;} 


} 

namespace mynamespace 

public class Derived : Base { 

    // some other properties of the derived class , not so relevant.... 
} 


public class Prop { 

    public String propString {get; set;} 
} 

: 나는 아래의 상황을 묘사 property (이 경우 문자열은 "Prop.propString"이되며이 메서드의 결과는 해당 속성이있는 PropertyInfo 개체 여야합니다.)

두 번째 것은 객체의 인스턴스를 가져오고 propString 속성 (이 경우 함수가 가져올 객체는 파생 객체)에서 조작을 수행해야합니다. "다소간"그런 식으로 구현 될 수 있다는 것을 알았지 만 지금은 제대로 작동하지 않습니다.

public void SecondFunc(Base obj) 
{ 
     PropertyInfo propertyInfo; 
     object obj = new object(); 
     string value = (string)propertyInfo.GetValue(obj, null); 

     string afterRemovalValue = myManipulationStringFunc(value); 

     propertyInfo.SetValue(obj, afterRemovalValue, null); 

} 

이러한 두 가지 기능을 구현하는 방법에 대한 조언을 제공해 주시고, 더 깊은 통찰력을 주시면 감사하겠습니다.

미리 감사드립니다.

가이.

답변

1

나는 당신이 성취하려는 것이 확실하고 최선의 방법인지 잘 모릅니다. 하지만 코드가 변경되도록 변경했습니다. 나는 ...

public class Base 
{ 
    public Prop prop { get; set; } 
} 

public class Derived : Base 
{ 

    // some other properties of the derived class , not so relevant.... 
} 

public class Prop 
{ 

    public String propString { get; set; } 
} 
public class MyClass 
{ 
    public void SecondFunc(object obj) 
    { 
     Type type = obj.GetType(); 
     var allClassProperties = type.GetProperties(); 
     foreach (var propertyInfo in allClassProperties) 
     { 
      if (propertyInfo.PropertyType == typeof(Prop)) 
      { 
       var pVal = (Prop)propertyInfo.GetValue(obj, null); 
       if(pVal == null) 
       { 
        //creating a new instance as the instance is not created in the ctor by default 
        pVal = new Prop(); 
        propertyInfo.SetValue(obj, pVal, null); 
       } 
       this.SecondFunc(pVal); 
      } 
      else if (propertyInfo.PropertyType == typeof(string)) 
      { 
       string value = (string)propertyInfo.GetValue(obj, null); 
       string afterRemovalValue = myManipulationStringFunc(value); 

       propertyInfo.SetValue(obj, afterRemovalValue, null); 
      } 
     } 
    } 

    private string myManipulationStringFunc(string value) 
    { 
     if (string.IsNullOrEmpty(value)) 
      value = "Value was NULL"; 
     return value; 
    } 
} 

난이 도움이되기를 바랍니다 ... 그것은 동적이 될 수하지 않았