C#通用類型轉換 Convert.ChangeType


http://technet.microsoft.com/zh-cn/library/system.convert.changetype(en-us).aspx

http://www.cnblogs.com/youring2/archive/2012/07/26/2610035.html

 

Example:

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

 

 

  名稱 說明
公共方法 靜態成員 ChangeType(Object, Type) 返回一個指定類型的對象,該對象的值等效於指定的對象。
公共方法 靜態成員 ChangeType(Object, TypeCode) 返回指定類型的對象,其值等效於指定對象。
公共方法 靜態成員 ChangeType(Object, Type, IFormatProvider) 返回指定類型的對象,其值等效於指定對象。 參數提供區域性特定的格式設置信息。
公共方法 靜態成員 ChangeType(Object, TypeCode, IFormatProvider) 返回指定類型的對象,其值等效於指定對象。 參數提供區域性特定的格式設置信息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM