访问不同的属性值有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; }
}
有一个错字:第二个'bc.DoSomething();'应'dr.DoSomething( );' – BartoszKP
错字固定,但它仍然返回A,答: –
是的,现在考虑Sriram Sakthivel的答案,它会很好:) – BartoszKP