[英]can i override a method with a derived class as its parameter in c#
I have a question about override in c#. 我对C#中的重写有疑问。 Why I can't override a method with a derived class as its parameter in c#?
为什么我无法在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)
{
}
}
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. 如果您不关心方法的多态性,则可以添加一个具有相同名称但具有不同(甚至派生更多)参数(作为重载)的方法,但是它不会是覆盖以前版本的vtable(虚拟)方法父类中的方法。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.