内隐式类型转换的泛型方法 [英] implict type cast in generic method

查看:200
本文介绍了内隐式类型转换的泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到一个编译错误在下面的代码说明:无法implicty型SpecialNode都转换为T 即使T必须从NodeBase我在where子句中定义的派生?而即使SpecialNode实际上是从NodeBase衍生

 公共静态牛逼GetNode< T>()其中T:NodeBase 
{
如果(typeof运算(T)== typeof运算(SpecialNode))
{
返回ThisStaticClass.MySpecialNode; //< - 编译器错误
}
如果(typeof运算(T)== typeof运算(OtherSpecialNode))
{
返回ThisStaticClass.MyOtherSpecialNode; //< - 编译器错误
}

返回默认值(T);
}


解决方案

编译器不读你的如果检查意识到,在这一行, T 必须 SpecialNode



您需要转换为 NodeBase 第一,是这样的:

 收益率(T)(NodeBase)MySpecialNode; 

您需要蒙上因为(只要编译器知道) T 可能是 MyOtherSpecialNode ,你不能投了 MyOtherSpecialNode MySpecialNode



修改:您可以使用一个投这样做:

  NodeBase retVal的; 

如果(typeof运算(T)== typeof运算(SpecialNode))
retVal的= MySpecialNode;
,否则如果(typeof运算(T)== typeof运算(OtherSpecialNode))
retVal的= MyOtherSpecialNode;

回报率(T)retVal的;


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 in the where clause and even though SpecialNode actually derived from NodeBase?

    public static T GetNode<T>() where T : NodeBase
    {
        if (typeof(T) == typeof(SpecialNode))
        {
            return ThisStaticClass.MySpecialNode; // <-- compiler error
        }
        if (typeof(T) == typeof(OtherSpecialNode))
        {
            return ThisStaticClass.MyOtherSpecialNode; // <-- compiler error
        }
        ...
        return default(T);
    }

解决方案

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;

这篇关于内隐式类型转换的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆