我有一个像这样的基类“父母”:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Parent
{
private int parentVirtualInt = -1;
public virtual int VirtualProperty
{
get
{
return parentVirtualInt;
}
set
{
if(parentVirtualInt != value)
{
parentVirtualInt = value;
}
}
}
}
}
和一个像这样的子类:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Child : Parent
{
public override int VirtualProperty
{
get
{
if(base.VirtualProperty > 0)
{
throw new ApplicationException("Dummy Ex");
}
return base.VirtualProperty;
}
set
{
if(base.VirtualProperty != value)
{
base.VirtualProperty = value;
}
}
}
}
}
请注意, Child 中的 getter 正在调用 Parent 的 getter(或者至少这是我的意图)。
我现在通过实例化“Child”类来使用它,为其 VirtualProperty 分配一个值(比如说 4),然后再次读取该属性。
Child c = new Child();
c.VirtualProperty = 4;
Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty);
当我运行它时,我显然得到一个 ApplicationException 说“Dummy Ex”。但是如果我在行上设置一个断点
if(base.VirtualProperty > 0)
在 Child 中并在抛出异常之前base.VirtualProperty
检查(通过将鼠标悬停在它上面)的值(我假设(d)),我已经得到了异常。由此,我传达了“儿童吸毒者自称”中的陈述;有点儿。base.VirtualProperty
我想要实现的是当我将parentVirutalInt
(在 Parent 中)的定义更改为 protected 并base.parentVirtualInt
在 Child 的 Getter 中使用而不是base.VirtualProperty
. 而且我还不明白为什么这不起作用。任何人都可以对此有所了解吗?我觉得被覆盖的属性的行为与被覆盖的方法不同?
顺便说一句:我正在做一些与我无法控制的类的子类化非常相似的事情(这是我的“解决方法”不是一个选项的主要原因)。
亲切的问候