ASP.NET: Shadowing Issues

情到浓时终转凉″ 提交于 2019-12-13 03:41:05

问题


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)


回答1:


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




回答2:


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

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



回答3:


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



来源:https://stackoverflow.com/questions/5560278/asp-net-shadowing-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!