以下是微軟技術(shù)資源庫的解說:http://technet.microsoft.com/zh-cn/library/system.convert.changetype
ChangeType 是將 value 指定的對象轉(zhuǎn)換為 conversionType 的通用轉(zhuǎn)換方法。 value 參數(shù)可以是任何類型的對象,conversionType 也可以是表示任何基類型或自定義類型的 Type 對象。要使轉(zhuǎn)換成功,value 必須實(shí)現(xiàn) IConvertible 接口,因為此方法只是包裝對相應(yīng) IConvertible 方法的調(diào)用。 此方法要求支持將 value 轉(zhuǎn)換為 conversionType。
/// <summary>
/// 為模型的單個屬性賦值
/// </summary>
/// <param name="obj"></param>
/// <param name="PropertyName"></param>
/// <param name="val"></param>
/// <returns></returns>
public static bool SetVal(object obj, string PropertyName, object val)
{
PropertyDescriptorCollection PropertyCollection = TypeDescriptor.GetProperties(obj);
if (PropertyCollection.Count > 0)
{
PropertyDescriptor Property = PropertyCollection[PropertyName];
if (Property != null)
{
var temp = ChangeType(val, Property.PropertyType);
Property.SetValue(obj, temp);
return true;
}
}
return false;
}
/// <summary>
/// 類型轉(zhuǎn)換
/// </summary>
/// <param name="obj"></param>
/// <param name="type"></param>
/// <returns></returns>
private static object ChangeType(object obj, Type type)
{
Type nulltype = Nullable.GetUnderlyingType(type);
if (nulltype != null)
{
if (obj == null)
{
return null;
}
return Convert.ChangeType(obj, nulltype, Thread.CurrentThread.CurrentCulture);
}
if (typeof(System.Enum).IsAssignableFrom(type))
{
return Enum.Parse(type, obj.ToString());
}
return Convert.ChangeType(obj, type, Thread.CurrentThread.CurrentCulture);
}