using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Data; namespace ConsoleApplication11 { class Program { static void Main(string[] args) { var dt = new DataTable(); dt.Columns.Add("c1", typeof(string)); var row = dt.NewRow(); row["c1"] = "abc"; var c = getDataFromDBField<double>(row["c1"], 2); //返回2 var d = getDataFromDBField<object>(row["c1"], 2); //返回"abc" } private static T getDataFromDBField<T>(object obj, T defaultValue = default(T)) { if (obj == null || obj == DBNull.Value) return defaultValue; Type t = typeof(T);
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) //支持可空类型
t = t.GetGenericArguments()[0];
var tryParse = t.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder , new Type[] { obj.GetType() , t.MakeByRefType() } , new ParameterModifier[] { new ParameterModifier(2) }); if (tryParse != null) { var parameters = new object[] { obj, Activator.CreateInstance(t) }; bool success = (bool)tryParse.Invoke(null, parameters); if (success) return (T)parameters[1]; else return defaultValue; } return (T)Convert.ChangeType(obj, typeof(T)); } } }