C# method generic return type casting

前端 未结 3 406
悲哀的现实
悲哀的现实 2020-12-10 15:32

I am trying to create a method in an interface with a generic return type but I fail to cast the generic to a specific type/class. But if I put the generic on the interface

3条回答
  •  一生所求
    2020-12-10 16:10

    The second code snippet is impossible to compile because Rain is not T.

    When the type parameter is supplied in the class, there's no problem because the method can only return the type that was already supplied in the class declaration. In other words - T foo() becomes Rain foo.

    However, when the type parameter is supplied to the method, then the method is obligated to return whatever type is supplied to it - so you can't return anything other than T. In other words, the compiler can't enforce the calling method to only use foo(), but it can enforce the foo method to return T.

提交回复
热议问题