将抽象只读属性覆盖为读/写属性 [英] Override abstract readonly property to read/write property

查看:22
本文介绍了将抽象只读属性覆盖为读/写属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想强制在基本抽象类的给定属性上实现 C# getter.如果需要,派生类还可以为该属性提供一个 setter,以供静态绑定类型的公共使用.

I would like to only force the implementation of a C# getter on a given property from a base abstract class. Derived classes might, if they want, also provide a setter for that property for public use of the statically bound type.

给定以下抽象类:

public abstract class Base
{
    public abstract int Property { get; }
}

如果我想要一个也实现了 setter 的派生类,我可以天真地尝试:

If I want a derived class that also implements a setter, I could naively try:

public class Derived : Base
{
    public override int Property
    {
        get { return field; }
        set { field = value; } // Error : Nothing to override.
    } 

    private int field;
}

但是后来我收到一个语法错误,因为我试图覆盖不存在的 setter.我尝试了一些其他方法,例如将 base setter 声明为私有等等,但我仍然偶然发现了各种阻止我这样做的错误.必须有办法做到这一点,因为它不会破坏任何基类契约.

But then I get a syntax error since I try to override the non existing setter. I tried some other way such as declaring the base setter private and such and I still stumble upon all kind of errors preventing me from doing that. There must be a way to do that as it doesn't break any base class contract.

顺便说一句,它可以用接口来完成,但我真的需要那个默认实现.

Incidentaly, it can be done with interfaces, but I really need that default implementation.

我经常遇到这种情况,我想知道是否有隐藏的 C# 语法技巧可以做到这一点,否则我只能忍受它并实现手动 SetProperty() 方法.

I stumbled into that situation so often, I was wondering if there was a hidden C# syntax trick to do that, else I will just live with it and implement a manual SetProperty() method.

推荐答案

你不能直接做,因为你不能用相同的newoverride同一类型的签名;有两个选项 - 如果您控制基类,请添加 second 属性:

You can't do it directly, since you can't new and override with the same signature on the same type; there are two options - if you control the base class, add a second property:

public abstract class Base
{
    public int Property { get { return PropertyImpl; } }
    protected abstract int PropertyImpl {get;}
}
public class Derived : Base
{
    public new int Property {get;set;}
    protected override int PropertyImpl
    {
        get { return Property; }
    }
}

否则你可以在类层次结构中引入一个额外的层次:

Else you can introduce an extra level in the class hierarchy:

public abstract class Base
{
    public abstract int Property { get; }
}
public abstract class SecondBase : Base
{
    public sealed override int Property
    {
        get { return PropertyImpl; }
    }
    protected abstract int PropertyImpl { get; }
}
public class Derived : SecondBase
{
    public new int Property { get; set; }

    protected override int PropertyImpl
    {
        get { return Property; }
    }
}

这篇关于将抽象只读属性覆盖为读/写属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆