使用反射设置对象的属性 [英] Set object property using reflection

查看:133
本文介绍了使用反射设置对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在.NET C#3.5我可以使用反射来设置对象属性?

Is there a way in .NET c# 3.5 I can use reflection to set an object property?

例如:

MyObject obj = new MyObject();
obj.Name = "MyName";

我想设置 obj.Name 与反思。是这样的:

I want to set obj.Name with reflection. Something like:

Reflection.SetProperty(obj, "Name") = "MyName";

是否有这样做的方法吗?

Is there a way of doing this?

推荐答案

是的,你可以使用 Type.InvokeMember()

using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
    Type.DefaultBinder, obj, "MyName");

这将抛出一个异常,如果 OBJ 并没有一个所谓的房地产名称,也可以不进行设置。

This will throw an exception if obj doesn't have a property called Name, or it can't be set.

另一种方法是获得的元数据属性,然后将其设置。这将允许您检查属性的存在,并验证它可以设置:

Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:

using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
    prop.SetValue(obj, "MyName", null);
}

这篇关于使用反射设置对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆