How do you wrap the 'Convert' class into a Generic function
Below is a simplified example of what I want to do. In the actual code I catch exceptions to do other things. But essentially I would like to wrap the 'Convert' class in a generic function, but alas this code generates an error saying that it cannot implicitly convert from type 'ushort' to 'T'.
Any ideas gratefully received. (It's my first question so go gentle with me!)
private T ChangeValue<T>(T value, string x)
{
if (typeof(UInt16) == typeo开发者_JAVA百科f(T))
{
value = Convert.ToUInt16(x);
}
return value;
}
Are you looking for something like this?
private T ChangeType<T>(object value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
Usage:
double result = ChangeType<double>(true);
精彩评论