can i override a method with a derived class as its parameter in c#

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-17 06:12:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!