如何在 C# 中使用反射将具有不同数据类型的属性设置为字符串值?

csharpserver side programmingprogramming更新于 2025/6/26 9:22:17

反射是指托管代码可以读取自身的元数据来查找程序集。本质上,它允许代码检查同一系统中的其他代码。借助 C# 中的反射,我们可以动态创建某个类型的实例,并将该类型绑定到现有对象。此外,我们还可以从现有对象中获取类型并访问其属性。当我们在代码中使用属性时,反射允许我们访问,因为它提供了描述模块、程序集和类型的 Type 对象。

假设我们有一个 double 类型的属性,在运行时我们实际上将其值设置为字符串,并在更改类型后将其赋值给该属性。我们可以使用 Convert.ChangeType() - 它允许我们使用任何 IConvertible 类型的运行时信息来更改表示格式。

示例

using System;
using System.Reflection;
namespace DemoApplication{
   class Program{
      static void Main(){
         Circle circle = new Circle();
         string value = "6.5";
         PropertyInfo propertyInfo = circle.GetType().GetProperty("Radius");
         propertyInfo.SetValue(circle, Convert.ChangeType(value,
         propertyInfo.PropertyType), null);
         var radius = circle.GetType().GetProperty("Radius").GetValue(circle, null);
         Console.WriteLine($"Radius: {radius}");
         Console.ReadLine();
      }
   }
   class Circle{
      public double Radius { get; set; }
   }
}

输出

Radius: 6.5

在上面的例子中,我们可以看到字符串值"6.5"使用 Convert.ChangeType 转换为实际类型 double,并在运行时使用反射分配给 Radius 属性。


相关文章