开发者

ASP.NET: Shadowing Issues

I have two classes in two separate libraries (one VB, one C#):

Public Class Item
    ...
    Public Overridable ReadOnly Property TotalPrice() As String
    Get
        Return FormatCurrency(Price + SelectedOptionsTotal())
    End Get
End Property
End Class

and

public class DerivedItem : Item {
    ...
   public new Decimal TotalPrice
    {
        get { return Price + OptionsPrice; }
    }
}

As you can see, the DerivedItem.TotalPrice shadows the Item.TotalPrice property. However, when tr开发者_运维问答ying to retrieve the DerivedItem.TotalPrice value, I'm still getting the base object's TotalPrice value.

Why is the DerivedItem's property not being returned?

EDIT

I've actually found the problem! I am getting the wrong value in the JSON string being returned via AJAX. It turns out that the TotalPrice is being returned correctly, it's just being overwritten by the shadowed property call being made later in the JSON string. My new question, then, is how to I prevent the shadowed property from being serialized?

(This question has been rescoped here)


It may depend on how you are instantiating the object.

For example:

DerivedItem i = new DerivedItem();
i.TotalPrice();

Will call the shadowed version.

However:

Item i = new DerivedItem();
i.TotalPrice();

Will actually call the base.

Here's a nice explanation.

Of course if at all possible I would avoid shadowing.... :-)


Are you referecing TotalPrice from a reference to the base type?

Item item = new DerivedItem;
string s = item.TotalPrice;


Does setting <NonSerialized()> attribute on the base class property work?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜