在覆盖财产的吸引力中呼唤"基地 - 吸气者"

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.我还不明白为什么这不起作用.任何人都可以对此有所了解吗?我觉得被覆盖的属性与被覆盖的方法的行为不同?

顺便说一句:我正在做一些非常相似的事情,我没有任何控制权的子类(这是我的"解决方法"不是一个选项的主要原因).

亲切的问候

Han*_*ant 8

它(可以说)是调试器中的一个错误.您可以将此投票添加到此反馈文章中.这很难修复,我敢肯定,调试器没有现成的基本属性getter方法地址访问权限,因为属性getter的v-table插槽已在派生类中被替换.

一种可能的解决方法是首先将基值存储在局部变量中,以便检查该变量.这不会让你的吸气速度变慢.