![](/img/trans.png)
[英]Can you add a Derived Class to a list of its base class then call a method of the Derived class from the list of base class in C#
[英]can i override a method with a derived class as its parameter in c#
我对C#中的重写有疑问。 为什么我无法在c#中覆盖带有派生类作为其参数的方法?
像这样:
class BaseClass
{
}
class ChildClass:BaseClass
{
}
abstract class Class1
{
public virtual void Method(BaseClass e)
{
}
}
abstract class Class2:Class1
{
public override void Method(ChildClass e)
{
}
}
由于类型不变/矛盾
这是一个简单的思想实验,使用您的类定义:
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?
如果您不关心方法的多态性,则可以添加一个具有相同名称但具有不同(甚至派生更多)参数(作为重载)的方法,但是它不会是覆盖以前版本的vtable(虚拟)方法父类中的方法。
class Class2 : Class1 {
public void Method(ChildClass e) {
}
}
另一个选择是重写,但可以分支并委托给基本实现,或者对所使用的参数的假设作出断言:
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
}
}
}
要么:
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.