修改基于 class 的派生 class 值
modifying derived class values from base class
是否可以在基础 class 中使用一种方法来修改派生的 class' 属性?我在想这样的事情:
public class baseclass
{
public void changeProperties(string propertyName, string newValue)
{
try
{
this.propertyName = newValue;
}
catch
{
throw new NullReferenceException("Property doesn't exist!");
}
}
}
您可以通过反射解决您的问题,因为 this
引用的类型将等于实际类型,即派生类型 class:
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);
}
}
是否可以在基础 class 中使用一种方法来修改派生的 class' 属性?我在想这样的事情:
public class baseclass
{
public void changeProperties(string propertyName, string newValue)
{
try
{
this.propertyName = newValue;
}
catch
{
throw new NullReferenceException("Property doesn't exist!");
}
}
}
您可以通过反射解决您的问题,因为 this
引用的类型将等于实际类型,即派生类型 class:
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);
}
}