implict type cast in generic method

后端 未结 7 1236
刺人心
刺人心 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:16

    See my answer from a previous post

    Using Generics to return a literal string or from Dictionary

    but the answer is

    return (T)MySpecialNode
    

    Because even you do the if check the compiler does not so you have to recast to T

提交回复
热议问题