我有这样的基础“父母”:

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;
                }
            }
        }
    }
}

请注意,儿童的Getter正在调用父母的待遇(或至少这是我打算的)。

现在,我通过对“儿童”类实例化,将值(例如4)分配给其VirtualProperty,然后再次阅读该属性。

Child c = new Child();
c.VirtualProperty = 4;
Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty);

当我运行此功能时,显然我会得到一个applicationException,说“虚拟ex”。 如果我在行上设置一个断点

if(base.VirtualProperty > 0)

在孩子中检查 base.VirtualProperty (通过将鼠标悬停在其上) 在抛出例外之前 (我假设(d)),我已经得到例外。我从中传达了这一说法 base.VirtualProperty 在“儿童呼唤自己”中;有点儿。

我想实现的是我在更改定义时得到的相同的行为 parentVirutalInt (在父母中)保护和使用 base.parentVirtualInt 在孩子的getter中而不是 base.VirtualProperty. 。而且我还没有明白为什么这不起作用。有人可以对此提供一些启示吗?我觉得覆盖的属性的行为与覆盖方法不同吗?

顺便说一句:我正在做一些非常相似的事情,而不是对我没有任何控制的班级(这是我的“解决方法”不是一个选择的主要原因)。

亲切的问候

有帮助吗?

解决方案

这是(可以说)调试器中的一个错误。您可以将投票添加到此 反馈文章. 。我敢肯定,这并不容易修复,由于在派生的类中替换了属性Getter的V台式插槽,因此调试器没有准备好访问基本属性Getter方法地址。

一种可能的解决方法是首先将基本值存储在局部变量中,以便您可以检查一个。这不会使您的Getter慢慢。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top