c#泛型TryParse类型转换

2021-05-11 04:27

阅读:443

标签: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 = getDataFromDBFielddouble>(row["c1"], 2);   //返回2
            var d = getDataFromDBFieldobject>(row["c1"], 2);   //返回"abc"
        }

        private static T getDataFromDBField(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


评论


亲,登录后才可以留言!