首页 / C#开发 / 正文

C#/.NET应用程序编程开发中如何使用反射设置对象的属性值?

2558 1 发布于: 2019-06-19 读完约需8分钟

问题描述

比如有类似这样的类Customer.cs

public class Customer
{
    public int Id{get;set;}
    public string FirstName{get;set;}
    public string LastName{get;set;}
}

在通常情况下,我们可以通过对象直接为属性赋值,如:

public static void Main()
{
    var customer = new Customer();
    customer.Id=1;
    customer.FirstName = "Rector" ;
    customer.LastName = "Liu";
}

在C#/.NET应用程序编程开发中,如何使用反射动态设置或者改变对象的属性值呢?

方案一

使用Type.InvokeMember()方法设置对象的属性值,如下(完整示例):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
  public static void Main()
  {
    var customer = new Customer();
    customer.GetType().InvokeMember("Id", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,Type.DefaultBinder,customer, new object[]{1});
    Console.WriteLine($"Id:{customer.Id}");
  }
}

public class Customer
{
  public int Id{get;set;}
  public string FirstName{get;set;}
  public string LastName{get;set;}
}

运行结果:

Id:1

如果对象customer没有指定的属性,则此方法会抛出异常。

方案二

使用Type.GetProperty()方法获取对象属性信息PropertyInfo,然后调用PropertyInfo.SetValue()方法设置对象的属性值,如下(完整示例):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
  public static void Main()
  {
    var customer = new Customer();
    PropertyInfo prop = customer.GetType().GetProperty("Id", BindingFlags.Public | BindingFlags.Instance);
    if(null != prop && prop.CanWrite)
    {
        prop.SetValue(customer, 1, null);
    }
    Console.WriteLine($"Id:{customer.Id}");
  }
}

public class Customer
{
  public int Id{get;set;}
  public string FirstName{get;set;}
  public string LastName{get;set;}
}

运行结果:

Id:1

方案三

PropertyInfo.SetValue()方法的封装,如下:

public static class PropertyExtension{       

   public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
   {
    PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
    Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
    object safeValue = (value == null) ? null : Convert.ChangeType(value, t);

    property.SetValue(p_object, safeValue, null);
   }
}

方案四

使用第三方类库FastMember,使用示例如下:

static void Main(string[] args)
{
    var customer = new Customer();
    var wrapped = ObjectAccessor.Create(customer);
    wrapped["Id"] = 1;
    wrapped["FirstName"] = "Rector";
    Console.WriteLine($"Id:{customer.Id}");
    Console.WriteLine($"FirstName:{customer.FirstName}");
    Console.ReadLine();
}

输出结果:

Id:1
FirstName:Rector

温馨提示:本文标注有(完整示例)的示例代码可以直接粘贴在try.dot.net中运行。

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: C#/.NET应用程序编程开发中如何根据一个文件的扩展名获取对应的MIME类型?

下一篇: C#/.NET应用程序编程开发中更简易,更高效的方式读/写文件有哪些?

本文永久链接码友网 » C#/.NET应用程序编程开发中如何使用反射设置对象的属性值?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册