」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用反射在C#中動態設置屬性值?

如何使用反射在C#中動態設置屬性值?

發佈於2025-04-08
瀏覽:521

How Can I Set Property Values Dynamically in C# Using Reflection?
使用Reflection

可以使用C#中的反射動態設置屬性的值。 This allows you to modify an object's property at runtime, regardless of its accessibility or visibility.

To set a property value using reflection, follow these steps:

Get the PropertyInfo Object:

Use Type.GetProperty to retrieve the PropertyInfo object associated with the property you want to modify.如果屬性不是公開的,則可能需要指定其他綁定標誌,例如bindingflags.nonpublic或bindingflags.instance。

一旦擁有propertyInfo對象,請調用其setValue方法實際設置了該屬性的值。此方法採用兩個參數:您要修改的對象實例和要設置的新值。
    以下示例演示瞭如何使用反射來設置一個人類類的firstName屬性:
  1. args) { //創建一個人類的實例 人p = new Person(); //獲取propertyInfo對象的firstName屬性 var屬性= typeof(person).getProperty(“ firstName”); //使用反射設置名稱屬性的值 property.setValue(p,“約翰”,null); //打印一個名稱屬性的值 Console.Writeline(P.FirstName); //約翰 } } 在此示例中,屬性變量將引用對人類類的名稱屬性。使用P實例和字符串值“ John”調用SetValue方法,以動態設置屬性的值。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3