覆盖获取,但不能设置 [英] Override Get, But Not Set
问题描述
我有一个抽象类,定义了一个 GET
,而不是设置
,因为据该抽象类而言,它只需要一个 GET
。
I have an abstract class that defines a get
, but not set
, because as far as that abstract class is concerned, it needs only a get
.
public abstract BaseClass
{
public abstract double MyPop
{get;}
}
然而,在一些派生类的,我需要一个设置
属性,所以我在看这个实施
However, in some of the derive class, I need a set
property, so I am looking at this implementation
public class DClass: BaseClass
{
public override double MyPop
{get;set;}
}
现在的问题是,我得到一个编译错误,说
The problem is, I got a compilation error, saying that
*设定:无法重写,因为*。没有一个重写的set访问。
*.set: cannot override because *. does not have an overridable set accessor.
尽管我认为上面的语法是完全合法的。
Even though I think that the above syntax is perfectly legitimate.
对此有何想法?解决方法,或者为什么会是这样
Any idea on this? Workaround, or why this is so?
的 修改:我能想到的唯一方法是将两个 GET
和设置
作为抽象类,并让子类抛出一个 NotImplementedException
如果设置
被调用,这是没有必要的。这东西我不喜欢,有特殊setter方法一起 的
The only approach I can think of is to put both get
and set
as in the abstract class, and let the subclass throws a NotImplementedException
if set
is called and it's not necessary. That's something I don't like, along with a special setter method .
推荐答案
一个可能的答案是覆盖吸气,然后执行一个单独的setter方法。如果你不想在基本要定义的属性setter做,你没有太多其他选择。
One possible answer would be to override the getter, and then to implement a separate setter method. If you don't want the property setter to be defined in the base, you don't have many other options.
public override double MyPop
{
get { return _myPop; }
}
public void SetMyPop(double value)
{
_myPop = value;
}
这篇关于覆盖获取,但不能设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!