[英]C# abstract property that can be initialized in constructor but readonly afterwards?
In a class I have a property在一个班级我有一个财产
protected abstract string test{ get; }
When I try to initialize it in a constructor.当我尝试在构造函数中初始化它时。 I get an error saying:
我收到一条错误消息:
Property or indexer xxx cannot be assigned to.
无法分配属性或索引器 xxx。 -- it is read-only.
——它是只读的。
Is there a way to allow some property to be有没有办法允许某些财产
You likely don't want an abstract
property.您可能不想要
abstract
属性。 You would only use that if you wanted to force the derived class to provide a custom implementation.如果您想强制派生类提供自定义实现,您只会使用它。 In your case you simply want it to be set in the constructor and
readonly
.在您的情况下,您只希望在构造函数中设置它并
readonly
。
public abstract class Base
{
protected string MyProperty { get; }
public Base(string myProperty)
{
MyProperty = myProperty;
}
}
public class Derived : Base
{
public Derived()
: base("DefaultValue")
{ }
}
Simply implement the abstract method with a private setter in your derived class: 只需在派生类中使用私有设置器来实现abstract方法:
class Derived : Base
{
protected override string test { get; } = "MyInitialValue";
}
or before C#6 with a readonly backing-field:
class Derived : Base
{
private readonly string _test = "MyInitialValue";
protected override test { get { return this._test; } }
}
This allows you to set different values for different classes. 这使您可以为不同的类设置不同的值。 If you don´t need this and all classes should have the exact same value you can define it within your base-class my making it non-abstract.
如果您不需要它,并且所有类都应具有完全相同的值,则可以在基类中定义它,以使其成为非抽象的。
You can also use a private setter in your derived class. 您还可以在派生类中使用私有设置器。 This makes it readonly to other classes but you can set the value within your class outside the constructor also.
这使其对其他类只读,但您也可以在构造函数之外的类中设置值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.