sch*_*and 8 c# getter virtual overriding properties
我有一个基类"父"这样:
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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
和这样的子类:
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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,Child中的getter正在调用Parent的getter(或者至少这是我想要的).
我现在通过实例化它来使用"Child"类,为其VirtualProperty分配一个值(比方说4),然后再次读取该属性.
Child c = new Child();
c.VirtualProperty = 4;
Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty);
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我显然得到一个说"Dummy Ex"的ApplicationException.但是,如果我在线上设置断点
if(base.VirtualProperty > 0)
Run Code Online (Sandbox Code Playgroud)
在Child中并检查base.VirtualProperty(通过将鼠标悬停在它上面)的值,然后抛出异常(我假设(d)),我已经得到了异常.由此我转达base.VirtualProperty了"Child-Getter自称" 中的陈述; 的种类.
我想要实现的是当我将parentVirutalInt(在Parent中)的定义更改为protected并base.parentVirtualInt在Getter of Child中使用而不是使用时所获得的相同行为base.VirtualProperty.我还不明白为什么这不起作用.任何人都可以对此有所了解吗?我觉得被覆盖的属性与被覆盖的方法的行为不同?
顺便说一句:我正在做一些非常相似的事情,我没有任何控制权的子类(这是我的"解决方法"不是一个选项的主要原因).
亲切的问候