如何在C#中动态获取属性值?
我们可以利用反射来动态获取属性值。
反射提供了描述程序集,模块和类型的(类型为Type的)对象。我们可以使用反射来动态创建类型的实例,将类型绑定到现有对象,或者从现有对象获取类型并调用其方法或访问其字段和属性。如果我们在代码中使用属性,则反射使我们能够访问它们。
System.Reflection命名空间和System.Type类在.NETReflection中扮演重要角色。这两个共同作用,使我们能够反思类型的许多其他方面。
示例
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属性值。类似地,为了获取属性值,我们使用了反射类的GetProperty()方法。通过使用此方法,我们可以在运行时获取任何属性的值。
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西