如何在 C# 中动态获取属性值?

csharpserver side programmingprogramming更新于 2025/4/20 9:07:17

我们可以使用 Reflection 来动态获取属性值。

Reflection 提供描述程序集、模块和类型的对象(Type 类型)。我们可以使用 Reflection 来动态创建类型的实例,将类型绑定到现有对象,或者从现有对象获取类型并调用其方法或访问其字段和属性。如果我们在代码中使用属性,则 Reflection 使我们能够访问它们。

System.Reflection 命名空间和 System.Type 类在 .NET Reflection 中起着重要作用。这两个一起工作,使我们能够反映类型的许多其他方面。

示例

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

在上面的例子中,我们可以看到,通过获取类型和属性名称,使用 Reflection 来设置 Employee 属性值。同样,为了获取属性值,我们使用了 Reflection 类的 GetProperty() 方法。通过使用此方法,我们可以在运行时获取任何属性的值。


相关文章