c# - 在覆盖属性的 Getter 中调用 "Base-Getter"

标签 c# properties virtual overriding getter

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

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(在 Parent 中)的定义更改为 protected 并在 Getter 中使用 base.parentVirtualInt 时得到的相同行为的 Child 而不是 base.VirtualProperty。而且我还不明白为什么这不起作用。任何人都可以阐明这一点吗?我觉得重写属性的行为与重写方法不同?

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

亲切的问候

最佳答案

它(可以说)是调试器中的一个错误。您可以对此 feedback article 投上您的一票.这不容易修复,我敢肯定,调试器没有准备好访问基本属性 getter 方法地址,因为属性 getter 的 v 表槽已在派生类中被替换。

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

关于c# - 在覆盖属性的 Getter 中调用 "Base-Getter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2455667/

相关文章:

c# - 使用 ShellExecuteEx 打开资源管理器进程下的文件属性表,而不是调用进程

java - Ant:如何减去两个属性(包含时间戳)?

c++ - 虚拟类和多态性

java - 如何使用子gradle模块的application.properties?

c# - 如何禁止使用字段而不是属性?

c++ - 将抽象基类作为成员处理时的所有权问题

c# - 当我可以在派生类中隐藏它时,为什么我需要声明一个虚拟方法

c# - 如何绑定(bind)或以其他方式获取和设置资源中控件的值?

c# - ElasticSearch:如何在集合中搜索

C# 命名空间 : how to follow standards without causing annoying conflicts?