Dzwebs.Net

撰写电脑技术杂文十余年

C#实现通用类型的转换代码

Admin | 2013-10-8 14:06:50 | 被阅次数 | 4832

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  下面的代码功能,是用来实现通用类型的转换的。

  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);
        }


该杂文来自: 网站开发杂文

上一篇:程序设计流程图的常用符号及含义

下一篇:使用批处理命令重新启动网站应用程序池

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计