简体   繁体   中英

C# override base generic method cannot cast T to T?

Trying to override a method that returns the generic type.

The compiler error is:

CS0266 cannot implicit convert type 'T' to 'T?'.

Simple example:

public class Base
{
    public virtual T? Method<T>()
    {
        return default;
    }
}

public class Class : Base
{
    public override T? Method<T>()
    {
        return base.Method<T>();
    }
}

I understand that this is because the base method lacks a class constraint, but I am calling to the base method so there shouldn't be any conversion happening, right?

Thank you @lidqy, that article helped a lot. Found I could do this to get it to compile.

public class Base {
    public virtual T? Method<T>() {
        return default;
    }
}

public class Class : Base {
    [return: System.Diagnostics.CodeAnalysis.MaybeNull()]
    public override T Method<T>() {
        return base.Method<T>();
    }
}

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