【发布时间】:2014-12-18 06:37:32
【问题描述】:
我是 C# 新手,需要使用反射来执行特定任务。
事情是这样的:我有一个名为 Derived 的类,它派生自一个名为 Base 的类。在 Base 类中,我有另一个公共类,它是一个名为 Prop 类的属性。在 Prop 类中,有一个 String 类型的公共属性,称为 propString。 Derived 和 Base 类都在同一个命名空间下。我描述了以下情况:
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;}
}
我需要写两个函数:
第一个接收类中属性的“完整路径”字符串,需要提取该属性的类型(在我的情况下,字符串将是“Prop.propString”,并且此方法的结果需要成为具有该属性的 PropertyInfo 对象)。
第二个获取一个对象的实例并需要对 propString 属性执行操作(在我的情况下,该函数将获取的对象是 A Derived 对象)。 我知道它可以以“或多或少”的方式实现,但目前效果不佳。
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);
}
请您就如何实现这两个功能提出建议,当然,我们将非常感谢您提供任何进一步的见解。
提前致谢,
伙计。
【问题讨论】:
标签: c# reflection nested propertyinfo derived-types