现在的位置: 首页 > 综合 > 正文

利用泛型和反射编写通用基础类型转换方法

2013年05月11日 ⁄ 综合 ⁄ 共 3098字 ⁄ 字号 评论关闭

 

实际项目中,很经常是需要转换数据类型的,字符串转换为int类型,DateTime类型,为了避免经常要考虑转换的时候的异常,并且提高开发效率,我萌发了个编写可以在基础数据结构中进行相互转化的通用方法的念头。(这个实际编写的时间是我一年多前,我还在大学的时候编写的,没有去更改,可能有很多问题,望请赐教)

首先我说下使用的方法先,以下是单元测试代码

        [TestMethod()]
        public void ToObjecTest()
        {
            string str = "12";
            Assert.AreEqual(12, str.ToObject<int>());
            Assert.AreEqual(0, "12sdf".ToObject<int>());

            bool isConvertInt;
            Assert.AreEqual(0, "12sdf".ToObject<int>(out isConvertInt));
            Assert.IsFalse(isConvertInt);

            Assert.AreEqual(TestEnum.one, 1.ToObject<TestEnum>());
            Assert.AreEqual(TestEnum.two, 2.ToObject<TestEnum>());

            Assert.AreEqual(new DateTime(1922, 2, 2), "1922-2-2".ToObject<DateTime>());
            bool isConvertTime;
            Assert.AreEqual(DataExt.DefaultDateTime, "1222-2-30".ToObject<DateTime>(out isConvertTime));
            Assert.IsFalse(isConvertTime);
        }

        enum TestEnum
        {
            one = 1,
            two = 2
        }

 

ToObject<T>是一个扩展方法,可以看到使用起来是很方便的。

以下是类的实现代码

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Reflection;
  6   9     public static class DataConverter
 10     {
 11         /// <summary>
 12         /// 默认时间Date = {1991/1/1 0:00:00}
 13         /// </summary>
 14         public static DateTime DefaultDateTime { get { return new DateTime(1991, 1, 1); } }
 15         /// <summary>
 16         /// 默认时间日期Data = 1991-1-1
 17         /// </summary>
 18         public static string DefaultChinaDate { get { return "1991-1-1"; } }
 19 
 20         #region ToObject方法 类型转换,对null值做了处理
 21         /// <summary>
 22         /// 类型转换,对null值做了处理
 23         /// </summary>
 24         /// <typeparam name="T"></typeparam>
 25         /// <param name="data"></param>
 26         /// <param name="blnIsSuccess">是否转换成功</param>
 27         /// <returns></returns>
 28         public static T ToObject<T>(this object data, out bool blnIsSuccess)
 29         {
 30             blnIsSuccess = true;
 31             if (data == null)
 32             {
 33                 blnIsSuccess = false;
 34                 return ExcException<T>();
 35             }
 36             Type tDate = data.GetType();
 37             Type tT = typeof(T);
 38             try
 39             {
 40                 //枚举
 41                 if (tT.IsEnum)
 42                 {
 43                     object e = System.Enum.Parse(tT, data.ToString());
 44                     if (tT.GetEnumNames().Contains(e.ToString()))
 45                         return (T)e;
 46                     else
 47                     {
 48                         blnIsSuccess = false;
 49                         return ExcException<T>();
 50                     }
 51                 }
 52                 //可空的值类型 如int?、long?
 53                 if (tT.IsGenericType && tT.GetGenericTypeDefinition().BaseType == typeof(ValueType))
 54                 {
 55                     return (T)Convert.ChangeType(data, tT.GetGenericArguments()[0]);
 56 
 57                 }
 58                 return (T)Convert.ChangeType(data, tT);
 59             }
 60             catch (Exception)
 61             {
 62                 blnIsSuccess = false;
 63                 return ExcException<T>();
 64             }
 65         }
 66         /// <summary>
 67         /// 异常处理
 68         /// </summary>
 69         /// <typeparam name="T"></typeparam>
 70         /// <param name="blnIsSuccess"></param>
 71         /// <returns></returns>
 72         private static T ExcException<T>()
 73         {
 74             Type tT = typeof(T);
 75             if (typeof(DateTime).Equals(tT))
 76                 return (T)(object)DataExt.DefaultDateTime;
 77             if (tT.IsGenericType)
 78             {
 79                 return (T)Activator.CreateInstance(tT.GetGenericArguments()[0]);
 80             }
 81             if (tT.IsEnum)
 82             {
 83                 return (T)System.Enum.Parse(tT, tT.GetEnumNames()[0]);
 84             }
 85             return default(T);
 86         }
 87         /// <summary>
 88         /// 类型转换,对null值做了处理
 89         /// </summary>
 90         /// <typeparam name="T"></typeparam>
 91         /// <param name="data"></param>
 92         /// <returns></returns>
 93         public static T ToObject<T>(this object data)
 94         {
 95             bool blnIsSuccess;
 96             return data.ToObject<T>(out blnIsSuccess);
 97         }
 98 
 99         #endregion
100         /// <summary>
101         /// 转换为"yyyy-MM-dd"格式的时间字符串,对null做了处理
102         /// </summary>
103         /// <param name="data"></param>
104         /// <returns></returns>
105         public static string ToChinaDate(this DateTime data)
106         {
107             if (data == null) return DataExt.DefaultChinaDate;
108             return data.ToString("yyyy-MM-dd");
109         }
110 
111     }

 

 

 

 

抱歉!评论已关闭.