using System;
using System.ComponentModel;
public class Convertors
{
/// <summary>
/// See Convert.ChangeType.
/// </summary>
/// <typeparam name="T">New type, may be Nullable.</typeparam>
/// <param name="value">Object</param>
/// <returns>Typed object.</returns>
public static T ChangeType<T>(object value)
{
Type conversionType = typeof(T);
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default(T);
}
else
{
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
}
return (T)Convert.ChangeType(value, conversionType);
}
}
|