【问题标题】:Calling "Base-Getter" in Overriding Getter of Property在覆盖属性的 Getter 中调用“Base-Getter”
【发布时间】:2011-01-28 04:18:30
【问题描述】:

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

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)),我已经得到了异常。由此我传达了“Child-Getter 自称”中的声明base.VirtualProperty;那种。

我想要实现的是当我将parentVirutalInt(在父级中)的定义更改为受保护并在子级的获取器中使用base.parentVirtualInt 而不是base.VirtualProperty 时得到的相同行为。而且我还不明白为什么这不起作用。任何人都可以对此有所了解吗?我觉得被覆盖的属性的行为与被覆盖的方法不同?

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

亲切的问候

【问题讨论】:

    标签: c# properties virtual overriding getter


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2014-04-08
      • 2021-11-06
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多