对派生对象使用反射

本文关键字:反射 对象 派生 | 更新日期: 2023-09-27 18:34:37

我是C#的新手,需要使用反射执行某项任务。

事情是这样的:我有一个名为 Derived 的类,它派生出一个名为 Base 的类。在 Base 类中,我有另一个公共类,它是一个名为 Prop 类的属性。在 Prop 类中,有一个字符串类型的公共属性称为 propString。派生类和基类位于同一命名空间下。我在下面描述了情况:

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

请就如何实现这两个功能提供建议,当然,您的任何进一步见解将不胜感激。

提前感谢分配,

家伙。

对派生对象使用反射

我不确定您要完成什么以及这是否是最好的方法。但是我已经更改了代码,使其正常工作。我没有让它尽可能动态......

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

我希望这有帮助...