implict type cast in generic method

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

    You could also do:

    public static T GetNode() where T : NodeBase
    {
        T result;
    
        result = ThisStaticClass.MySpecialNode as T;
        if (result != null) return result;
    
        result = ThisStaticClass.MyOtherSpecialNode as T;
        if (result != null) return result;
    
        return default(T);
    }
    

    Edit: If the static classes are already null, this probably wouldn't have the intended effect.

提交回复
热议问题