“T"类型的值无法转换为 [英] Value of type 'T' cannot be converted to

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

问题描述

这可能是一个新手问题,但 google 出人意料地没有提供答案.

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.

谢谢!

推荐答案

即使它在 if 块内,编译器也不知道 T 是 <代码>字符串.
因此,它不允许您进行投射.(出于同样的原因,您不能将 DateTime 转换为 string)

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)

您需要转换为 object,(任何 T 都可以转换为),然后从那里转换为 string(因为 object 可以转换为 string).
例如:

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天全站免登陆