码迷,mamicode.com
首页 > Windows程序 > 详细

c#泛型TryParse类型转换

时间:2017-09-25 13:29:45      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:wro   creat   val   reflect   pre   odi   public   div   value   

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);
            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));
        }
    }
}

 

c#泛型TryParse类型转换

标签:wro   creat   val   reflect   pre   odi   public   div   value   

原文地址:http://www.cnblogs.com/nanfei/p/7591113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!