简体   繁体   English

如何覆盖抽象属性?

[英]How to Override abstract Property?

public abstract class SampleA
{
    public abstract string PropertyA {get;set;}
}

How to Override abstract PropertyA ?如何覆盖抽象 PropertyA ?

在此处输入图片说明

You are trying to override a property with a field您正在尝试使用字段覆盖属性

Properties provide access to a field by get and set value accessors.属性通过getset值访问器提供对字段的访问。 Please read this to better understand the difference.请阅读本文以更好地了解差异。 So because they are not the same, your IDE proposed you to hide the parent Property by using the new -Keyword.因此,由于它们不相同,您的 IDE 建议您使用new -Keyword 来隐藏父属性。

If you want to know why the new Keyword didn't work in your case, read this .如果您想知道为什么new关键字在您的情况下不起作用,请阅读

Improve your Design改进您的设计

In your Question, it seems like PropertyA in your code needs to be set on inherited classes, but can't be changed from outside.在您的问题中,您的代码中的PropertyA似乎需要在继承的类上设置,但不能从外部更改。 So maybe do it like this:所以也许这样做:

public abstract class SampleA
{
    // no setter -> cant be changed after initialization
    public abstract string PropertyA { get; } 

    // protected setter -> can only be changed from inside SampleA or Sample
    public abstract string PropertyB { get; protected set; } 
}

public class Sample : SampleA
{
    public override string PropertyA { get; } = "override";
    public override string PropertyB { get; protected set; } = "override";
}

How it's done with your current design您当前的设计是如何完成的

Do it like this:像这样做:

public class Sample : SampleA
{
    public override string PropertyA { get; set; } = "override";
}

or even implement it with more behavior:甚至用更多的行为来实现它:

public class Sample : SampleA
{
    private string _propertyA = "override";

    public override string PropertyA
    {
        get { return _propertyA; }
        set
        {
            // Maybe do some checks here
            _propertyA = value;
        }
    }
}

When you override your property you should write both get and set .当您覆盖您的属性时,您应该同时编写getset In your case you create a new property with the same name but with another signature.在您的情况下,您创建一个具有相同名称但具有另一个签名的新属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM