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

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

问题描述

我想只有从基抽象类强制C#吸气的实施在给定的属性。 。派生类可能,如果他们愿意,还提供了该财产供公众使用的静态绑定类型的二传手

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

如果我想要一个派生类还实现了一个二传手,我天真地尝试:

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



但后来我得到一个语法错误,因为我试图重写不存在的二传手。我尝试了一些其他的方式,例如,宣布基地二传手私人和这样的,我还是偶然发现的所有错误类型阻止我这样做的。必须有一个办法做到这一点,因为它不会破坏任何基类合同。

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,它可以用接口来完成,但我真的需要一个默认的实现

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.

推荐答案

您不能直接这样做,因为你不能覆盖与同类型相同的签名;有两种选择 - 如果你控制的基类,添加的第二的属性:

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天全站免登陆