///
/// 獲取類中的屬性值
///
///
///
///
public string GetModelValue(string FieldName, object obj)
{
try
{
Type Ts = obj.GetType();
object o = Ts.GetProperty(FieldName).GetValue(obj, null);
string Value = Convert.ToString(o);
if (string.IsNullOrEmpty(Value)) return null;
return Value;
}
catch
{
return null;
}
}
///
/// 設置類中的屬性值
///
///
///
///
public bool SetModelValue(string FieldName,string Value, object obj)
{
try
{
Type Ts = obj.GetType();
object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
Ts.GetProperty(FieldName).SetValue(obj, v, null);
return true;
}
catch
{
return false;
}
}
在網上找沒有找到,剛自己寫了一個方法,供分享.
在寫方法時這里有一個東西弄了很久沒有搞好.就是屬性類型如果是int 時,傳入string字串就會設置不成功.
這里我用到了Convert.ChangeType 轉換,根據屬性類型自動轉換.
REFERENCE FROM : http://blog.csdn.net/cestarme/article/details/6545529