implict type cast in generic method

后端 未结 7 1310
刺人心
刺人心 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条回答
  •  Happy的楠姐
    2021-01-19 10:15

    The compiler doesn't read your if check to realize that in this particular line, T must be SpecialNode.

    You need to cast to NodeBase first, like this:

    return (T)(NodeBase)MySpecialNode;
    

    You need to casts because (as far as the compiler knows) T might be MyOtherSpecialNode, and you cannot cast a MyOtherSpecialNode to MySpecialNode.

    EDIT: You can do it with a single cast like this:

    NodeBase retVal;
    
    if (typeof(T) == typeof(SpecialNode))
        retVal = MySpecialNode;
    else if (typeof(T) == typeof(OtherSpecialNode))
        retVal = MyOtherSpecialNode;
    
    return (T)retVal;
    

提交回复
热议问题