类型'T'的值不能转换为 [英] Value of type 'T' cannot be converted to

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

问题描述

这可能是AA新手的问题,但谷歌出人意料地并没有提供答案。

This is likely a a novice question, but google surprisingly did not provide an answer.

我有这样的,而人工方法

I have this rather artificial method

    T HowToCast<T>(T t)
    {
        if (typeof(T) == typeof(string))
        {
            T newT1 = "some text";
            T newT2 = (string)t;
        }

        return t;
    }

我来自一个C ++背景的我也期待这个工作。然而,它未能编译无法隐式转换类型'T'串和无法将类型'T'串对于上述两种分配。

Coming from a C++ background I have expected this to work. However, it fails to compile with "Cannot implicitly convert type 'T' to string" and "Cannot convert type 'T' to string" for both of the above assignments.

我要么做一些概念性错误的或者只是有错误的语法。请帮我解决这一个出来。

I am either doing something conceptually wrong or just have the wrong syntax. Please help me sort this one out.

感谢您!

推荐答案

尽管这是一个如果块里面,编译器不知道 T 字符串
因此,它不会让你投。 (对于您不能施放同样的原因的DateTime 字符串

Even though it's inside of an if block, the compiler doesn't know that T is string.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime to string)

您需要转换为对象,(其中任何 T 可强制转换为),并从那里字符串(因为对象可以转换为字符串)。< BR> 例如:

You need to cast to object, (which any T can cast to), and from there to string (since object can be cast to string).
For example:

T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;

这篇关于类型'T'的值不能转换为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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