天天看點

通用TryParse

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

using System.ComponentModel;

namespace NetService

{

public static class GenericParser

public static bool TryParse<T>(this string input, out T output)

bool result = false;

output = default(T);

try

var parse = TypeDescriptor.GetConverter(typeof(T));

if (parse != null)

output = (T)parse.ConvertFromString(input);

result = true;

}

catch

return result;

public static T ConvertType<T>(object val)

if (val == null) return default(T);//傳回類型的預設值

Type tp = typeof(T);

//泛型Nullable判斷,取其中的類型

if (tp.IsGenericType)

tp = tp.GetGenericArguments()[0];

//string直接傳回轉換

if (tp.Name.ToLower() == "string")

return (T)val;

//反射擷取TryParse方法

var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,

new Type[] { typeof(string), tp.MakeByRefType() },

new ParameterModifier[] { new ParameterModifier(2) });

var parameters = new object[] { val, Activator.CreateInstance(tp) };

bool success = (bool)TryParse.Invoke(null, parameters);

//成功傳回轉換後的值,否則傳回類型的預設值

if (success)

return (T)parameters[1];

return default(T);

繼續閱讀