2013-08-18 53 views
1

访问不同的属性值有ViewModelBase与派生DerivedViewModel我如何在派生类

ViewModelBase具有DoSomething()它访问AProperty

DerivedViewModel也使用DoSomething(),但它需要访问不同的对象。

背后的原因是ViewModel在屏幕上以及在对话框中使用。当它在屏幕中时,它需要访问特定的实体,但是当它在对话框中时,它需要访问不同的实体。

这是简化的代码。如果你运行它,它们都返回A,而不是A,然后返回B.所以问题是,如何返回A,然后返回B?

class Program 
{ 
    static void Main(string[] args) 
    { 
     ViewModelBase bc = new ViewModelBase(); 
     bc.DoSomething(); Prints A 

     DerivedViewModel dr = new DerivedViewModel(); 
     dr.DoSomething(); Prints A, would like it to print B. 


    } 
} 

public class ViewModelBase { 

    private string _aProperty = "A"; 

    public string AProperty { 
     get { 
      return _aProperty; 
     } 
    } 

    public void DoSomething() { 
     Console.WriteLine(AProperty); 
    } 

} 

public class DerivedViewModel : ViewModelBase { 

    private string _bProperty = "B"; 
    public string AProperty { 
     get { return _bProperty; } 


} 
+1

有一个错字:第二个'bc.DoSomething();'应'dr.DoSomething( );' – BartoszKP

+0

错字固定,但它仍然返回A,答: –

+0

是的,现在考虑Sriram Sakthivel的答案,它会很好:) – BartoszKP

回答

3

覆盖在派生类的属性

public class ViewModelBase 
{ 
    private string _aProperty = "A"; 
    public virtual string AProperty 
    { 
     get { return _aProperty; } 
    } 

    public void DoSomething() 
    { 
     Console.WriteLine(AProperty); 
    } 
} 

public class DerivedViewModel : ViewModelBase 
{ 
    private string _bProperty = "B"; 
    public override string AProperty 
    { 
     get { return _bProperty; } 
    } 
} 

DerivedViewModel dr = new DerivedViewModel(); 
dr.DoSomething();//Prints B 

此外看一看Msdn Polymorphism

+0

这正是我所寻找的。这个http://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new解释了它的工作原理(Override vs New) –