简体   繁体   中英

can i override a method with a derived class as its parameter in 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#?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM