8

我有一个像这样的基类“父母”:

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

顺便说一句:我正在做一些与我无法控制的类的子类化非常相似的事情(这是我的“解决方法”不是一个选项的主要原因)。

亲切的问候

4

1 回答 1

8

它(可以说)是调试器中的一个错误。您可以在此反馈文章中添加您的投票。这不容易解决,我敢肯定,调试器无法访问基本属性 getter 方法地址,因为属性 getter 的 v-table 插槽已在派生类中被替换。

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

于 2010-03-16T15:58:50.447 回答