如何使泛型类型铸造函数

可能的复制品:
是否有一个通用的 Parse ()函数可以使用 Parse 将字符串转换为任何类型?

我想创建一个通用函数来执行一些操作,比如:

ConvertValue<T>(string value)

如果 Tint,那么函数将把值转换为 int并返回结果。

类似地,如果 Tboolean,函数将把 value转换为 boolean并返回它。

怎么写?

126806 次浏览

Something like this?

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");

Edit:

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));
}

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.

ConvertValue( System.Object o ), then you can branch out by o.GetType() result and up-cast o to the types to work with the value.

While probably not as clean looking as the IConvertible approach, you could always use the straightforward checking typeof(T) to return a T:

public static T ReturnType<T>(string stringValue)
{
if (typeof(T) == typeof(int))
return (T)(object)1;
else if (typeof(T) == typeof(FooBar))
return (T)(object)new FooBar(stringValue);
else
return default(T);
}


public class FooBar
{
public FooBar(string something)
{}
}