2016-05-27 125 views
0

是否有可能在基类中有一个方法来修改派生类的属性?我想是这样的:从基类修改派生类的值

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

似乎给我一个代码味道。我更喜欢基类中的虚拟方法来进行修改。它可以在基类中为空,并在任何需要它的派生类中重载。 –

+0

如果你正在做类似'INotifyPropertyChanged'的实现,这是很常见的。不是propertyName,而是通过引用将属性传递给方法。虽然第二次看,你实际上是在试图重写属性的名称。你不能/不想这样做。 – Jonesopolis

回答

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