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
  • 相关阅读:
    java 抽象类
    ClassNotFoundException: dao.impl.ActionImpl
    侦听状态一直为T的处理
    Duplicate entry '1' for key 'PRIMARY'(报错)
    ibatis学习笔记
    java中的堆、栈和常量池
    servlet学习
    三大排序
    第一次面试??交流
    毕业季,学长,学姐们的践行
  • 原文地址:https://www.cnblogs.com/iiwen/p/4242457.html
Copyright © 2011-2022 走看看