铸造字符串泛型类型为字符串 [英] Casting string to generic type that is a string

查看:125
本文介绍了铸造字符串泛型类型为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写做一个聪明的类型转换的方法 - 使用的ToString()如果类型参数恰好是一个字符串,否则铸造但是返回null如果投不工作。基本上得到了的尽可能多的信息v 它可以在不抛出异常。



我检查 T 的确是一个字符串之前,我尝试中投,但编译器仍然不是一个球迷:

 无法转换类型'字符串'到'T'

这是我的方法:

 公共T'转换< T>(宾语)
{
如果(typeof运算(T)== typeof运算(字符串)){
回报率(T)v.ToString(); //不能键入'串'转换为'T'
}其他{试
返回(T)V;
}赶上(InvalidCastException的){
返回NULL;
}
}



也让我知道这是某种不可原谅罪。我用它来处理,可以有混合型的一些数据结构。


解决方案

您基本上需要通过<去code>对象强制转换为泛型类型时:

 收益率(T)(对象) v.ToString()

 收益率(T)(对象)诉; 



我会使用,而不是抓一个 InvalidCastException的虽然。



请参阅的Eric利珀特最近的博客文章对于为什么这是必要的更多细节。

$ b




由于编译器知道这种转换可能可能成功的唯一途径是,如果<:
$ b

在特定的code> U 是布尔,但 U 可以是任何东西!编译器假定大部分时间 U 不会与布尔构造,因此,这种代码几乎是肯定是一个错误,编译器把这个事实你注意。




(替换 T U 字符串布尔。 ..)


I'm writing a method to do a intelligent type conversion - using ToString() if the type parameter happens to be a string, otherwise casting but returning null if the cast doesn't work. Basically gets as much information out of v it can without throwing an exception.

I check that T is indeed a string before I attempt the cast, but the compiler is still not a fan:

Cannot convert type 'string' to 'T'

And here's my method:

public T? Convert<T>(object v)
{
    if (typeof(T) == typeof(string)) {
    return (T)v.ToString(); // Cannot convert type 'string' to 'T'  
    } else try {
      return (T)v;
    } catch (InvalidCastException) {
    return null;
    }
}

Also let me know if this is some sort of unforgivable sin. I'm using it to deal with some data structures that could have mixed types.

解决方案

You basically need to go via object when casting to a generic type:

return (T)(object) v.ToString()

and

return (T)(object) v;

I would use is rather than catching an InvalidCastException though.

See Eric Lippert's recent blog post for more details of why this is necessary.

In particular:

Because the compiler knows that the only way this conversion could possibly succeed is if U is bool, but U can be anything! The compiler assumes that most of the time U is not going to be constructed with bool, and therefore this code is almost certainly an error, and the compiler is bringing that fact to your attention.

(Substitute T for U and string for bool...)

这篇关于铸造字符串泛型类型为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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