尝试别的方法,一直找不到好的。
/// <summary>
/// 转成基本的类型(支持可空类型)
/// </summary>
public static T Convert<T>(this string str, T defaultValue)
{
if (String.IsNullOrEmpty(str))
return defaultValue;
var type = typeof(T);
var typeName = type.FullName;
if (type.Name == "Nullable`1")
{
var m = Regex.Match(typeName, @"((?<=\[)(\w+.\w+)(?=,))");
type = Type.GetType(m.Value);
}
MethodInfo method = null;
foreach (var m in type.GetMethods())
{
if (m.Name == "Parse" && m.GetParameters().Length == 1)
{
method = m;
break;
}
}
var result = defaultValue;
try
{
if (method != null)
result = (T)method.Invoke(null, new[] { str });
}
catch
{
return defaultValue;
}
return result;
}
/// 转成基本的类型(支持可空类型)
/// </summary>
public static T Convert<T>(this string str, T defaultValue)
{
if (String.IsNullOrEmpty(str))
return defaultValue;
var type = typeof(T);
var typeName = type.FullName;
if (type.Name == "Nullable`1")
{
var m = Regex.Match(typeName, @"((?<=\[)(\w+.\w+)(?=,))");
type = Type.GetType(m.Value);
}
MethodInfo method = null;
foreach (var m in type.GetMethods())
{
if (m.Name == "Parse" && m.GetParameters().Length == 1)
{
method = m;
break;
}
}
var result = defaultValue;
try
{
if (method != null)
result = (T)method.Invoke(null, new[] { str });
}
catch
{
return defaultValue;
}
return result;
}