implict type cast in generic method

后端 未结 7 1224
刺人心
刺人心 2021-01-19 09:47

why do I get a compiler error in the following code stating: Cannot implicty convert type SpecialNode to T even though T must derive from NodeBase as I defined

7条回答
  •  时光说笑
    2021-01-19 10:13

    The problem is that the function may be called with a type parameter T, which derives from NodeBase but not from SpecialNode. The compiler doesn't check the semantics of the if statement, so it doesn't know, that T has to be a specialNode.

    You would need to use an explicit cast to T in order to satisfy your compiler.

提交回复
热议问题