问题
I've got an ASP.NET usercontrol with a panel that I'm using to hide and show the content, that is,
<asp:Panel runat="server" ID=pnlContainer">
<!-- Some fairly uninteresting content -->
</asp:Panel>
I've got a visible property as an overrider, that is,
public override bool Visible
{
get { return pnlContainer.Visible; }
set { pnlContainer.Visible = value; }
}
When I set it I get a stack overflow exception BUT when I change the keyword to new
, that is,
public new bool Visible
{
get { return pnlContainer.Visible; }
set { pnlContainer.Visible = value; }
}
Everything works fine. Why is this? I think I've just got a generally poor understanding of these keywords and it's showing here.
Also:
If I put no keyword on - Visual Studio gives a warning saying that either the new
or the override
keyword should be used as I am masking an already existing member on the user control.
In a way, my strange practice of using a panel to control the visible on the user control isn't the issue here. With help of the contributors it's clearly mad and shouldn't be done. But the issue that interested me was that the override
and new
keywords behaved in such different ways and the reasons for this.
回答1:
The difference is summarized on the Microsoft page Knowing When to Use Override and New Keywords (C# Programming Guide).
Review the section of code indicated there. It is also listed below:
public static void TestCars2()
{
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
}
foreach (Car vehicle in cars)
{
System.Console.WriteLine("Car object: " + vehicle.GetType());
vehicle.DescribeCar();
System.Console.WriteLine("----------");
}
The same principle is getting applied to your source. The .NET framework treats all controls on the page as a collection of base Control classes. Control.Visible
is a virtual property.
This means: when the ASP.NET framework invokes Control.Visible
for all controls, the only Control.Visible
property that is invoked from your source is the one marked as override
, which is what people typically think of with standard polymorphism. Otherwise, if you declare your property as new
, when the ASP.NET framework invokes Control.Visible
, your property is never called.
Thus the override results in a stack overflow exception since you are then calling your panel.Visible
, which is recursively calling itself many times.
回答2:
The new
keyword hides an inherited member (see Knowing When to Use Override and New Keywords (C# Programming Guide) for an example).
So when you apply new
in this case, at some point the object is then being referenced as its base class, and the base class setter is being called instead of your derived class setter (which has an infinite loop because your setter calls itself).
来源:https://stackoverflow.com/questions/13162542/difference-between-c-sharp-new-and-override-keyword-on-property