有没有谁用过Convert.ChangeType来转自定义类型
怎么实现?
------解决方案--------------------
[code=c#]
public static object ChangeType(object value, Type conversionType, IFormatProvider provider)
{
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
}
if (value == null)
{
if (conversionType.IsValueType)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
}
return null;
}
IConvertible convertible = value as IConvertible;
if (convertible == null)
{
if (value.GetType() != conversionType)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
}
return value;
}
if (conversionType == ConvertTypes[3])
{
return convertible.ToBoolean(provider);
}
if (conversionType == ConvertTypes[4])
{
return convertible.ToChar(provider);
}
if (conversionType == ConvertTypes[5])
{
return convertible.ToSByte(provider);
}
if (conversionType == ConvertTypes[6])
{
return convertible.ToByte(provider);
}
if (conversionType == ConvertTypes[7])
{
return convertible.ToInt16(provider);
}
if (conversionType == ConvertTypes[8])
{
return convertible.ToUInt16(provider);
}
if (conversionType == ConvertTypes[9])
{
return convertible.ToInt32(provider);
}
if (conversionType == ConvertTypes[10])
{
return convertible.ToUInt32(provider);
}
if (conversionType == ConvertTypes[11])
{
return convertible.ToInt64(provider);
}
if (conversionType == ConvertTypes[12])
{
return convertible.ToUInt64(provider);
}
if (conversionType == ConvertTypes[13])
{
return convertible.ToSingle(provider);
}
if (conversionType == ConvertTypes[14])
{
return convertible.ToDouble(provider);
}
if (conversionType == ConvertTypes[15])
{
return convertible.ToDecimal(provider);
}
if (conversionType == ConvertTypes[0x10])
{
return convertible.ToDateTime(provider);
}
if (conversionType == ConvertTypes[0x12])
{
return convertible.ToString(provider);
}
if (conversionType == ConvertTypes[1])
{
return value;
}
return convertible.ToType(conversionType, provider);
}
[/code]
ChangeType的实现代码 看完你就知道该怎么用了