問題:得到一個實體類,包含其所有屬性的值,要修改其中的屬性值,但是要修改的屬性是變量,即不確定的屬性名稱。
代碼:
/// <summary>
/// 獲取屬性的值
/// </summary>
/// <typeparam name="T">實體類</typeparam>
/// <param name="t">實體</param>
/// <param name="property">屬性名稱</param>
/// <returns></returns>
public static Dictionary<object, object> GetPropertieValue<T>(T t,string property)
{
var ret = new Dictionary<object, object>();
if (t == null) { return null; }
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (properties.Length <= 0) { return null; }
foreach (PropertyInfo item in properties)
{
string name = item.Name;
object value = item.GetValue(t, null);
if (item.Name == property)
{
ret.Add(name, value);
}
}
return ret;
}