如何以 C# 動態獲取一個屬性值?
我們可以利用反射動態獲取一個屬性值。
反射提供了描述程式集、模組和型別的物件(即 Type 型別)。我們可以利用反射動態建立型別的例項,將型別繫結到現有物件,或者從現有物件獲取型別並呼叫其方法或獲取其欄位和屬性。如果在程式碼中使用屬性,反射將使我們能夠訪問這些屬性。
.NET 反射中,System.Reflection 名稱空間和 System.Type 類發揮了重要作用。這兩者協同工作,允許我們對型別的許多其他方面進行反射。
示例
using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var employeeType = typeof(Employee);
var employee = Activator.CreateInstance(employeeType);
SetPropertyValue(employeeType, "EmployeeId", employee, 1);
SetPropertyValue(employeeType, "EmployeeName", employee, "Mark");
GetPropertyValue(employeeType, "EmployeeId", employee);
GetPropertyValue(employeeType, "EmployeeName", employee);
Console.ReadLine();
}
static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) {
type.GetProperty(propertyName).SetValue(instanceObject, value);
}
static void GetPropertyValue(Type type, string propertyName, object instanceObject) {
Console.WriteLine($"Value of Property {propertyName}: {type.GetProperty(propertyName).GetValue(instanceObject, null)}");
}
}
public class Employee {
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
}輸出
以上程式碼的輸出是
Value of Property EmployeeId: 1 Value of Property EmployeeName: Mark
在以上示例中,我們可以看到,透過獲取型別和屬性名稱,反射設定 Employee 屬性值。類似地,為了獲取屬性值,我們使用了 Reflection 類的 GetProperty() 方法。透過使用這個方法,我們可以在執行時獲取任何屬性的值。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP