简体   繁体   中英

C# Possible to override a return type on derived classes?

class base{
    ....
    public string name();
    ....
}

class deriveda : base{
    ....
    public override string name();
    ....
}

class derivedb : base{
    ....
    public override string name();
    ....
}

class derivedc : base{
    ....
    public override foo name();
    ....
}

In most of my derived classes it's consistent but one of them I want to return a custom class type, is this possible?

Short answer is no.

Think of it, how will you use it later?

base b = new derivedc ()

And then? what will be the return type of b.name() ? string ? foo ?

You can however use generics to control it (although i'm not sure if it'll fit your use case):

class base<T>{
    ....
    public virtual T name();
    ....
}

class deriveda : base<string>{
    ....
    public override string name();
    ....
}

class derivedb : base<string>{
    ....
    public override string name();
    ....
}

class derivedc : base<foo>{
    ....
    public override foo name();
    ....
}

In c# 9, yes this should be possible, as long as the new type satisfies the covariance rules, in particular a more derived reference-type. It'll just work.

No , this is not possible. As pointed out by others, the compiler cannot distinguish between functions that differ only in return type (as return type is not part of the function signature).

One workaround (that might not work in your case) is to have your return type be a subclass of the base class functions's return type, as described here . However, foo cannot derive from string, because string is a sealed class. The closest you can get to deriving from predefined types like string is to define a string extension method as illustrated here .

Ofir's answer is probably your best choice, but this might give you other ideas.

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