开发者

How do I avoid an infinite loop when overriding a virtual property?

Is it possible to ignore set and get when I'm assigning to or retrieving a value?

In specific, I'm inheriting from a class that has a property declared like this:

virtual public Int32 Value { get; set; }

What I'd like to do is to override it and do something useful in those set and get's. The problem appears when I override it, I also have to manual开发者_运维知识库ly assign, or return the value from the property. If I do something like this:

override public Int32 Value
{
    get
    {
        return this.Value;
    }
    set
    {
        this.Value = value;
        // do something useful
    }

Then I'm creating an infinite loop. Is there a way to set or get the value without invoking the code in set and get, or do I have to make a separate name for the actual variable?


Instead of using this.Value, you should be using base.Value. That will retrieve/set the property in the base class.

Note that the base method actually has to be overridable (virtual or abstract); in your example it's not. If the base method is not virtual then you'll just get a compiler error when you try to override in the derived class.


The keyword you are after is base, documented here. This forces the compiler to resolve the property reference to the one defined in the base class. The VB.NET Equivalent is MyBase.

Thus:

get 
{ 
    return base.Value; 
} 
set 
{ 
    base.Value = value; 
    // do something useful 
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜