zoukankan      html  css  js  c++  java
  • C#通用类型转换 Convert.ChangeType 拓荒者

            static public object ChangeType(object value, Type type)
            {
                if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
                if (value == null) return null;
                if (type == value.GetType()) return value;
                if (type.IsEnum)
                {
                    if (value is string)
                        return Enum.Parse(type, value as string);
                    else
                        return Enum.ToObject(type, value);
                }
                if (!type.IsInterface && type.IsGenericType)
                {
                    Type innerType = type.GetGenericArguments()[0];
                    object innerValue = ChangeType(value, innerType);
                    return Activator.CreateInstance(type, new object[] { innerValue });
                }
                if (value is string && type == typeof(Guid)) return new Guid(value as string);
                if (value is string && type == typeof(Version)) return new Version(value as string);
                if (!(value is IConvertible)) return value;
                return Convert.ChangeType(value, type);
            } 

    今天在使用PetaPoco处理Nullable的时候出现了一个类型转化的问题,虽然最后发现是数据库类型错误,但在搜索过程中找到了这个通用的类型转换方法,觉得不错,留下来,也希望对更多的朋友提供帮助!

    原文链接:http://www.cnblogs.com/genson/archive/2008/10/08/1306099.html

  • 相关阅读:
    vi里面全局替换
    guanbi selinux
    ntop
    Java:求一个数组中连续子元素最大和
    LeetCode.643. 子数组最大平均数 I
    分治法-最大子数组问题
    Java实现最大连续子数组和
    golang xorm cmd xorm工具使用 reverse 反转一个数据库结构,生成代码
    golang中xorm的基本使用
    xorm入门
  • 原文地址:https://www.cnblogs.com/youring2/p/2610035.html
Copyright © 2011-2022 走看看