如何以 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