I remarked the compiler generates a warning if I suppress the override/new (Overloads/Shadows) keyword. Normally, I set the necessary keyword.
But what if i forget it?
// >>>> Case A - not virtual property -
class MyPoint : Point
{
int X { get; set; } // vs new int X { get; set; }
}
// >>>> Case B - virtual property -
class Foo
{
virtual int Value { get { return 0; } }
}
class Bar : Foo
{
// vs override/new int Value { get { return 1; } }
int Value { get {开发者_如何学C return 1; } }
}
Then you're not overriding the property, you're creating a new one, just as if you used the new
keyword.
Bar x = new Bar();
Foo y = x;
Console.WriteLine(x.Value); // Uses Bar.Value
Console.WriteLine(y.Value); // Uses Foo.Value
This is usually clearer when demonstrated with methods - in this case even when you override, you're still ending up with a separate backing fields in both classes, it's just that one of the fields will be redundant. Without overriding, you've got two backing fields, and which one you access via the property will depend on the compile-time type of the expression you're using to access it.
If you forget override
/new
, Value will function just as if you put new
before it.
It depends on your goal. If you're creating a "new" method, you can actually leave out the "new" keyword, and just deal with the warning. "new" exists for clarity.
On the other hand, if your intention is to override the inherited virtual method, leaving out "override" will actually end up creating a "new" method instead, and the inherited method will not be overridden.
精彩评论