You can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.
http://msdn.microsoft.com/en-us/library/ms173152.aspxhttp://msdn.microsoft.com/en-us/library/6fawty39.aspx
public class BaseClass { public virtual void DoWork() { } public virtual int WorkProperty { get { return 0; } } } public class DerivedClass : BaseClass { public override void DoWork() { } public override int WorkProperty { get { return 0; } } }
DerivedClass B = new DerivedClass(); B.DoWork(); // Calls the new method. BaseClass A = (BaseClass)B; A.DoWork(); // Also calls the new method.
In C#, derived classes can contain methods with the same name as base class methods.
- The base class method must be defined virtual.
- If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
- If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.
- The base class method can be called from within the derived class using the base keyword.
- The override, virtual, and new keywords can also be applied to properties, indexers, and events.
class GraphicsClass { public virtual void DrawLine() { } public virtual void DrawPoint() { } public virtual void DrawRectangle() { } }
class YourDerivedGraphicsClass : GraphicsClass { public override void DrawRectangle() { } }
base.DrawRectangle();
Alternatively, you can prevent the warning by using the keyword new in your derived class definition:
class YourDerivedGraphicsClass : GraphicsClass { public new void DrawRectangle() { } }
Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior.
Override and Method Selection
No comments:
Post a Comment