我ViewModelBase
有一个派生的DerivedViewModel
ViewModelBase
有DoSomething()
访问AProperty
DerivedViewModel也使用DoSomething()
,但它需要访问不同的对象。
背后的原因是ViewModel用于屏幕以及Dialog。当它在屏幕中时,它需要访问特定实体,但在对话框中,它需要访问不同的实体。
这里简化了代码。如果你运行它,它们都返回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; }
}
答案 0 :(得分: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