1

我有ViewModelBase一个派生的DerivedViewModel

ViewModelBaseDoSomething()哪些访问权限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; }


}
4

1 回答 1

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多态性

于 2013-08-18T16:18:06.360 回答