Last active
November 4, 2016 15:00
-
-
Save bymyslf/ad22d6211a42e20f2522fcdbfc6cea20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public static class ConvertExtensions | |
{ | |
public static T To<T>(this object obj) | |
{ | |
try | |
{ | |
Type type = typeof(T); | |
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))) | |
{ | |
if (obj == null) | |
{ | |
return (T)(object)null; | |
} | |
return (T)Convert.ChangeType(obj, Nullable.GetUnderlyingType(type)); | |
} | |
if (typeof(Enum).IsAssignableFrom(type)) | |
{ | |
return ConvertToEnum<T>(obj); | |
} | |
return ConvertTo<T>(obj); | |
} | |
catch (Exception ex) | |
{ | |
} | |
return default(T); | |
} | |
private static T ConvertToEnum<T>(object obj) | |
{ | |
Type type = typeof(T); | |
if (obj is string) | |
{ | |
return (T)Enum.Parse(type, (string)obj, true); | |
} | |
return (T)Enum.ToObject(type, obj); | |
} | |
private static T ConvertTo<T>(object obj) | |
{ | |
if (obj.IsNull()) | |
{ | |
return default(T); | |
} | |
Type type = typeof(T); | |
TypeConverter converter = TypeDescriptor.GetConverter(type); | |
if (converter.IsNotNull() && converter.CanConvertFrom(obj.GetType())) | |
{ | |
return (T)converter.ConvertFrom(obj); | |
} | |
return (T)Convert.ChangeType(obj, type); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment