C#獲取動態字段(屬性)的實體屬性值

問題:得到一個實體類,包含其所有屬性的值,要修改其中的屬性值,但是要修改的屬性是變量,即不確定的屬性名稱。

代碼:

/// <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;
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章