问题
I have a question about override in c#. Why I can't override a method with a derived class as its parameter in c#?
like this:
class BaseClass
{
}
class ChildClass:BaseClass
{
}
abstract class Class1
{
public virtual void Method(BaseClass e)
{
}
}
abstract class Class2:Class1
{
public override void Method(ChildClass e)
{
}
}
回答1:
Because of type invariance/contravariance
Here's a simple thought experiment, using your class definitions:
Class1 foo = new Class1();
foo.Method( new BaseClass() ); // okay...
foo.Method( new ChildClass() ); // also okay...
Class1 foo = new Class2();
foo.Method( new BaseClass() ); // what happens?
Provided you don't care about method polymorphism, you can add a method with the same name but different (even more-derived) parameters (as an overload), but it won't be a vtable (virtual) method that overrides a previous method in a parent class.
class Class2 : Class1 {
public void Method(ChildClass e) {
}
}
Another option is to override, but either branch and delegate to the base implementation, or make an assertion about what you're assuming about the parameters being used:
class Class2 : Class1 {
public override void Method(BaseClass e) {
ChildClass child = e as ChildClass;
if( child == null ) base.Method( e );
else {
// logic for ChildClass here
}
}
}
or:
class Class2 : Class1 {
public override void Method(BaseClass e) {
ChildClass child = e as ChildClass;
if( child == null ) throw new ArgumentException("Object must be of type ChildClass", "e");
// logic for ChildClass here
}
}
来源:https://stackoverflow.com/questions/32832719/can-i-override-a-method-with-a-derived-class-as-its-parameter-in-c-sharp