是否可以在基类中使用方法来修改派生类'属性?我在想这样的事情:
public class baseclass
{
public void changeProperties(string propertyName, string newValue)
{
try
{
this.propertyName = newValue;
}
catch
{
throw new NullReferenceException("Property doesn't exist!");
}
}
}
答案 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);
}
}