Covariance and Contravariance with Func in generics

前端 未结 5 2010
夕颜
夕颜 2021-01-02 06:51

I need more information about variance in generics and delegates. The following code snippet does not compile:

Error CS1961 Invalid variance: The ty

5条回答
  •  隐瞒了意图╮
    2021-01-02 07:05

    remove the in and out key words:

    public interface Test
    {
        TOut F (Func transform);
    }
    

    you can read about the meaning of them here:

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-generic-modifier

    A type can be declared contravariant in a generic interface or delegate if it is used only as a type of method arguments and not used as a method return type

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-generic-modifier

    The type parameter is used only as a return type of interface methods and not used as a type of method arguments.

提交回复
热议问题