如何在 C# 中透過反射設定屬性值?


System.Reflection 名稱空間包含可讓你獲取應用程式資訊以及動態新增型別、值和物件到應用程式的類。

反射物件用於在執行時獲取型別資訊。可訪問正在執行程式元資料的類位於 System.Reflection 名稱空間中。

反射允許在執行時檢視屬性資訊。

反射允許檢查程式集中各種型別並例項化這些型別。

反射允許方法和屬性的延遲繫結。

反射允許在執行時建立新型別,然後使用這些型別執行一些任務。

示例

GetProperty(String)

搜尋具有指定名稱的公共屬性。

GetType(String, Boolean)

獲取具有指定名稱的 Type 物件,位於程式集例項中,並且如果沒有找到型別,可選擇引發異常。

SetValue(Object, Object)

設定指定物件的屬性值。

class Program{
   static void Main(string[] args){
      User user = new User();
      Type type = user.GetType();
      PropertyInfo prop = type.GetProperty("Name");
      prop.SetValue(user, "Bangalore", null);
      System.Console.WriteLine(user.Name);
      Console.ReadLine();
   }
}
class User{
   public int Id { get; set; }
   public string Name { get; set; }
}

輸出

Bangalore

更新於: 2020 年 11 月 5 日

6K+ 瀏覽

開啟您的 職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.