Last active
April 29, 2021 11:12
-
-
Save NDiiong/948e19d4d10e3655b234c599418cc593 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
public static class ParseExtension | |
{ | |
private static CultureInfo _cultureInfo = CultureInfo.CurrentCulture; | |
public static T As<T>(this object value) | |
{ | |
var toType = typeof(T); | |
if (value == null) return default(T); | |
if (value is string) | |
{ | |
if (toType == typeof(Guid)) | |
return As<T>(new Guid(Convert.ToString(value, _cultureInfo)), _cultureInfo); | |
if ((string)value == string.Empty && toType != typeof(string)) | |
return As<T>(null, _cultureInfo); | |
} | |
else | |
{ | |
if (typeof(T) == typeof(string)) | |
return As<T>(Convert.ToString(value, _cultureInfo), _cultureInfo); | |
} | |
if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) | |
toType = Nullable.GetUnderlyingType(toType); | |
var canConvert = toType is IConvertible || (toType.IsValueType && !toType.IsEnum); | |
if (canConvert) | |
return (T)Convert.ChangeType(value, toType, _cultureInfo); | |
return (T)value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment