类型'T'的值不能转换为转换为、类型

2023-09-02 10:28:22 作者:断梦残念

这可能是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;