如何使一个泛型类型转换功能 [英] How to make a Generic Type Cast function

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

问题描述

可能重复:结果
是否有将使用解析字符串转换为任何类型的通用parse()函数?

我想打一个通用的功能做一些操作,如

I want to make a generic function for doing some operations, like

ConvertValue<T>(string value)

如果T是整数,那么函数将其转换价值为int和同样的返回结果
,如果T为布尔值,函数将其转换价值布尔并返回。

If T is int then function will convert value to int and return the result Similarly, if T is boolean, function will convert value to boolean and return it.

如何写?

推荐答案

这样呢?

public static T ConvertValue<T>(string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

您可以使用它是这样的:

You can then use it like this:

int val = ConvertValue<int>("42");



编辑:

您甚至可以做到这一点更通用的,而不是靠参数提供的类型字符串 U 工具 IConvertible - 这意味着你必须虽然指定两个类型参数:

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

public static T ConvertValue<T,U>(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}



我认为抓住了 InvalidCastException的的异常可能是由 Convert.ChangeType() - 但你会在这种情况下返回? 默认(T)?它似乎更适合具有来电显示处理的除外。

I considered catching the InvalidCastException exception that might be raised by Convert.ChangeType() - but what would you return in this case? default(T)? It seems more appropriate having the caller deal with the exception.

这篇关于如何使一个泛型类型转换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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