ASP.NET: Shadowing Issues

2019-09-05 13:46发布

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 trying 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)

3条回答
唯我独甜
2楼-- · 2019-09-05 14:26

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

查看更多
太酷不给撩
3楼-- · 2019-09-05 14:29

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

Item item = new DerivedItem;
string s = item.TotalPrice;
查看更多
劫难
4楼-- · 2019-09-05 14:52

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.... :-)

查看更多
登录 后发表回答