Could anyone tell me is there any other way a method can be overridden without using virtual/abstract/override in C#/.NET, Please provide me with an example.Please provide with an example... (what i am thinking is Extension methods am i correct.....)
相关问题
- how to define constructor for Python's new Nam
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
You can use the "new" keyword on your method to "hide" a method that was not declared as abstract/virtual, however if the method is called from a variable type-casted as the base class, it won't call your new method. This is the similar to overriding.
Example:
Extension methods allow you to add new methods to any class even if you don't have their source code or they're sealed. This is not the same as overriding
Another option is to use interfaces so that you can have two completely different objects that both have the same method, but when called from a variable type-casted as the interface, it looks similar to overriding.
You could also use a form of Proxy Mocking framework like Microsoft Moles, or CastleWindsor -> They have a way of instantiating a "proxy" object that has the same interface as the real object, but can provide a different implementation for each method.
No, there is no other way. You can hide an existing method with
new
if the base method is not marked asvirtual
, however it does not have the same effect (there is no polymorphism - the call will be dispatched based on the variable type, not on the actual object type).Extension will not work in this case. Objects own properties and methods take precedence. However you can overload a method using extensions.
You can override methods defined in the extensions, by keeping your extensions closer in the namespace to the place where you are going to use it.
Example: