遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

通用数据类型转换函数-针对基元类型的包括可空类型

        protected T TryParser<T>(object v, T dValue)
        {

            if (v == null)
            {
                return dValue;
            }
            else
            {
                T t = default(T);
                try
                {
                    if (t == null)//可空类型
                    {
                        Type type = typeof(T);

                        TypeConverter conv = TypeDescriptor.GetConverter(type);
                        t = (T)conv.ConvertFrom(v);
                    }
                    else
                    {

                        t = (T)Convert.ChangeType(v, typeof(T));
                    }
                }
                catch
                {

                    t = dValue;
                }
                return t;
            }
        }
        protected T TryParser<T>(string v, T dValue)
        {
            if (string.IsNullOrEmpty(v))
            {
                return dValue;
            }
            else
            {
                T t = default(T);
                try
                {
                    if (t == null)//可空类型
                    {
                        Type type = typeof(T);

                        TypeConverter conv = TypeDescriptor.GetConverter(type);
                        t = (T)conv.ConvertFrom(v);
                    }
                    else
                    {

                        t = (T)Convert.ChangeType(v, typeof(T));
                    }
                }
                catch
                {

                    t = dValue;
                }
                return t;
            }
        }

判断可空类型

bool IsNullableType(Type theType)
{
    return (theType.IsGenericType && theType.
      GetGenericTypeDefinition().Equals
      (typeof(Nullable<>)));
}

可空类型的测试

 //====转换成string 表示形式========

        public static string ConverToStr(object obj)
        {
 
            if (obj.GetType().IsPrimitive || obj is string )
            {
                return obj.ToString();
            }
            if(IsNullable(obj.GetType()))
            {
                return obj.ToString();
            }
            //执行xml序列化
            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
            StringBuilder sb = new StringBuilder();
            xmlSerializer.Serialize(new StringWriter(sb), obj);

 

            return sb.ToString();
        }
        private static bool IsNullable(Type t)
        {
            return t.IsGenericType && t.GetGenericTypeDefinition()==typeof(Nullable<>);
        }

 

posted on 2012-09-08 08:12  遗忘海岸  阅读(313)  评论(0编辑  收藏  举报