とを見て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
お役に立てれば。