AI编程助手
AI免费问答

如何在C#中通过反射设置属性值?

WBOY   2023-08-27 15:49   631浏览 转载

如何在c#中通过反射设置属性值?

系统。反射命名空间包含的类允许您获取有关应用程序的信息以及向应用程序动态添加类型、值和对象。

反射对象用于在运行时获取类型信息。允许访问正在运行的程序的元数据的类位于 System.反射命名空间。

反射允许在运行时查看属性信息。

反射允许检查程序集中的各种类型并实例化这些类型。

反射允许后期绑定到方法和属性。

反射允许在运行时创建新类型,然后使用这些类型执行一些任务。

示例

GetProperty(String)

搜索具有指定名称的公共属性。

GetType(String, Boolean)

获取程序集实例中具有指定名称的 Type 对象,并可以选择引发异常如果未找到类型。

SetValue(Object, Object)

设置指定对象的属性值。

class Program{
   static void Main(string[] args){
      User user = new User();
      Type type = user.GetType();
      PropertyInfo prop = type.GetProperty("Name");
      prop.SetValue(user, "Bangalore", null);
      System.Console.WriteLine(user.Name);
      Console.ReadLine();
   }
}
class User{
   public int Id { get; set; }
   public string Name { get; set; }
}

输出

Bangalore
声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除