从基类修改派生类值

时间:2016-05-27 13:42:36

标签: c# reflection derived-class base-class

是否可以在基类中使用方法来修改派生类'属性?我在想这样的事情:

public class baseclass
{
  public void changeProperties(string propertyName, string newValue)
  {
    try
    {
      this.propertyName = newValue;
    }
    catch
    {
      throw new NullReferenceException("Property doesn't exist!");
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以通过反射解决您的问题,因为this引用的类型将等于实际类型,即派生类的类型:

<强> Solution:

public class baseclass
{
    public void changeProperties(string propertyName, object newValue)
    {            
        var prop = GetType().GetProperty(propertyName);
        if (prop == null)
            throw new NullReferenceException("Property doesn't exist!");
        else
            prop.SetValue(this, newValue);
    }
}

<强>实施

public class Test : baseclass
{
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();
        test.changeProperties("Age", 2);
    }
}