我可以在 C# 中用派生类作为其参数覆盖方法吗 [英] can i override a method with a derived class as its parameter in c#

查看:56
本文介绍了我可以在 C# 中用派生类作为其参数覆盖方法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 C# 中覆盖的问题.为什么我不能在 c# 中覆盖以派生类作为参数的方法?

I have a question about override in c#. Why I can't override a method with a derived class as its parameter in 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)
    {
    }
}

推荐答案

因为类型不变/逆变

这是一个简单的思想实验,使用您的类定义:

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?

如果你不关心方法的多态性,你可以添加一个名称相同但参数不同(甚至更多派生)的方法(作为重载),但它不会覆盖父类中先前方法的 vtable(虚拟)方法.

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
        }
    }
}

或:

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
    }
}

这篇关于我可以在 C# 中用派生类作为其参数覆盖方法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆