看看Convert.ChangeType
和TypeDescriptor.GetConverter
。
我已经为我编写了一个扩展方法来做到这一点:
public static T Convert<T>(this object obj)
{
T result;
try
{
result = (T)System.Convert.ChangeType(obj, typeof(T));
if (object.ReferenceEquals(result, null))
{
var typeConverter = !obj.IsNullable()
? TypeDescriptor.GetConverter(typeof(T))
: new NullableConverter(typeof(T));
result = obj is string
? (T)typeConverter.ConvertFromString(obj as string)
: (T)typeConverter.ConvertTo(obj, typeof(T));
}
}
catch (Exception)
{
result = default(T);
}
return result;
}
public static bool IsNullable<T>(this T obj)
{
return Nullable.GetUnderlyingType(typeof(T)) != null;
}
用法:
var itemsToConvert = new[] { "4", "5.98", "false", DateTime.Now.ToString() };
var @int = itemsToConvert[0].Convert<int>();
var @double = itemsToConvert[1].Convert<double>();
var @bool = itemsToConvert[2].Convert<bool>();
var @dateTime = itemsToConvert[3].Convert<DateTime>();
Console.WriteLine(@"int: {0}, Type: {1}", @int, @int.GetType());
Console.WriteLine(@"double: {0}, Type: {1}", @double, @double.GetType());
Console.WriteLine(@"bool: {0}, Type: {1}", @bool, @bool.GetType());
Console.WriteLine(@"DateTime: {0}, Type: {1}", @dateTime, @dateTime.GetType());
输出:
int:4,类型:System.Int32
double:5.98,类型:System.Double
bool:False,类型:System.Boolean
DateTime:2013/08/21 06:01:07 PM,类型:System.DateTime
希望这可以帮助。