zoukankan      html  css  js  c++  java
  • c#泛型TryParse类型转换

    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)); } } }
  • 相关阅读:
    大型网站数据库架构分析
    Mysql 存储引擎中InnoDB与Myisam的主要区别
    设计模式培训之一:为什么要用单例模式?
    架构师成长之路
    hdoj1257 最少拦截系统
    hdoj2571 命运
    hdoj1010 Temperor of the bone
    hdoj1175 连连看
    ny220 推桌子
    ny168 房间安排
  • 原文地址:https://www.cnblogs.com/nanfei/p/7591113.html
Copyright © 2011-2022 走看看