C# 如何在派生类中访问不同的属性值
我有C# 如何在派生类中访问不同的属性值,c#,C#,我有ViewModelBase和派生的DerivedViewModel ViewModelBase具有访问a属性的DoSomething() DerivedViewModel也使用DoSomething(),但它需要访问不同的对象 这背后的原因是ViewModel在屏幕上以及对话框中使用。当它在屏幕中时,它需要访问特定的实体,但在对话框中时,它需要访问不同的实体 这里是简化的代码。如果你运行它,它们都返回A,而不是A,然后是B。所以问题是,如何返回A,然后是B class Program {
ViewModelBase
和派生的DerivedViewModel
ViewModelBase
具有访问a属性的DoSomething()
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; }
}
重写派生类中的属性
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
进一步看一下有一个输入错误:第二个bc.DoSomething()代码>应该是dr.DoSomething()代码> Type固定,但它仍然返回A,A是的,现在考虑Sriram Sakthivel的答案,这将是很好的:)这正是我正在寻找的。这就解释了它工作的原因(覆盖与新建)