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

    //转换对象的成任何类型
    //通用型
    //效率不见得有多高
    //当做特殊情况处理或者练习的话可以


    public static object ChangeType(object value, Type type)
    {
        if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
        if (value == nullreturn 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);





    //转载自  http://www.cnblogs.com/youring2/archive/2012/07/26/2610035.html
  • 相关阅读:
    memcached连接说明
    在win下启动memcached
    Memcached 查看帮助
    HTTP请求信息和响应信息的格式
    购买服务器配置带宽算法
    PHP删除数组指定下标的值
    tp5 验证器使用
    tp5 验证码功能实现
    layui 关闭当前窗口,刷新父级页面
    layui icon样式1到7
  • 原文地址:https://www.cnblogs.com/iiwen/p/4242457.html
Copyright © 2011-2022 走看看