繁体   English   中英

使用反射设置 object 属性

[英]Set object property using reflection

C# 中是否有一种方法可以使用反射来设置 object 属性?

前任:

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

我想用反射设置obj.Name 就像是:

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

有没有办法做到这一点?

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

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

如果obj没有名为Name的属性,或者无法设置它,这将引发异常。

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

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, "Value", null);
}

你也可以这样做:

Type type = target.GetType();

PropertyInfo prop = type.GetProperty("propertyName");

prop.SetValue (target, propertyValue, null);

其中 target 是将设置其属性的 object。

反射,基本上,即

myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);

或者有一些库可以在便利性和性能方面提供帮助; 例如使用FastMember

var wrapped = ObjectAccessor.Create(obj); 
wrapped[property] = "Bob";

(这还有一个好处是不需要提前知道是字段还是属性)

或者您可以将 Marc 的一个衬垫包裹在您自己的扩展 class 中:

public static class PropertyExtension{       

   public static void SetPropertyValue(this object obj, string propName, object value)
    {
        obj.GetType().GetProperty(propName).SetValue(obj, value, null);
    }
}

并这样称呼它:

myObject.SetPropertyValue("myProperty", "myValue");

为了更好地衡量,让我们添加一个方法来获取属性值:

public static object GetPropertyValue(this object obj, string propName)
{
        return obj.GetType().GetProperty(propName).GetValue (obj, null);
}

是的,使用System.Reflection

using System.Reflection;

...

    string prop = "name";
    PropertyInfo pi = myObject.GetType().GetProperty(prop);
    pi.SetValue(myObject, "Bob", null);

使用这样的东西:

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);
    property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
   }
}

或者

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);
   }
}

您还可以使用类似的方式访问字段:

var obj=new MyObject();
FieldInfo fi = obj.GetType().
  GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)

通过反射,一切都可以成为一本打开的书:) 在我的示例中,我们绑定到一个私有实例级字段。

当您想使用属性名称从另一个 Object 批量分配 Object 的属性时,可以试试这个:

public static void Assign(this object destination, object source)
    {
        if (destination is IEnumerable && source is IEnumerable)
        {
            var dest_enumerator = (destination as IEnumerable).GetEnumerator();
            var src_enumerator = (source as IEnumerable).GetEnumerator();
            while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
                dest_enumerator.Current.Assign(src_enumerator.Current);
        }
        else
        {
            var destProperties = destination.GetType().GetProperties();
            foreach (var sourceProperty in source.GetType().GetProperties())
            {
                foreach (var destProperty in destProperties)
                {
                    if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                    {
                        destProperty.SetValue(destination,     sourceProperty.GetValue(source, new object[] { }), new object[] { });
                        break;
            }
        }
    }
}

我刚刚发布了 Nuget package,它不仅允许设置第一级属性,还允许在给定的 object 中设置任何深度的嵌套属性。

这是package

通过从根开始的路径设置 object 的属性值。

object 可以是一个复杂的 object,该属性可以是多级深度嵌套属性,也可以是根目录下的属性。 ObjectWriter将使用属性路径参数查找属性并更新其值。 属性路径是从根到我们要设置的结束节点属性访问的属性的附加名称,由分隔符字符串参数分隔。

用法:

要直接在 object 根目录下设置属性:

IE。 LineItem class 有一个名为ItemId的 int 属性

LineItem lineItem = new LineItem();

ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);

要在 object 根下设置嵌套属性多个级别:

IE。 Invite class 有一个名为State的属性,它有一个名为Invite (Invite 类型)的属性,它有一个名为Recipient的属性,它有一个名为Id的属性。

更复杂的是, State属性不是引用类型,而是struct

以下是如何在一行中设置 object 树底部的 Id 属性(“outlook”的字符串值)。

Invite invite = new Invite();

ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");

根据 MarcGravell 的建议,我构建了以下 static 方法。该方法通常使用FastMember将源 object 中的所有匹配属性分配给目标

 public static void DynamicPropertySet(object source, object target)
    {
        //SOURCE
        var src_accessor = TypeAccessor.Create(source.GetType());
        if (src_accessor == null)
        {
            throw new ApplicationException("Could not create accessor!");
        }
        var src_members = src_accessor.GetMembers();
        if (src_members == null)
        {
            throw new ApplicationException("Could not fetch members!");
        }
        var src_class_members = src_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
        var src_class_propNames = src_class_members.Select(x => x.Name);
        var src_propNames = src_members.Except(src_class_members).Select(x => x.Name);

        //TARGET
        var trg_accessor = TypeAccessor.Create(target.GetType());
        if (trg_accessor == null)
        {
            throw new ApplicationException("Could not create accessor!");
        }
        var trg_members = trg_accessor.GetMembers();
        if (trg_members == null)
        {
            throw new ApplicationException("Could not create accessor!");
        }
        var trg_class_members = trg_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
        var trg_class_propNames = trg_class_members.Select(x => x.Name);
        var trg_propNames = trg_members.Except(trg_class_members).Select(x => x.Name);



        var class_propNames = trg_class_propNames.Intersect(src_class_propNames);
        var propNames = trg_propNames.Intersect(src_propNames);

        foreach (var propName in propNames)
        {
            trg_accessor[target, propName] = src_accessor[source, propName];
        }
        foreach (var member in class_propNames)
        {
            var src = src_accessor[source, member];
            var trg = trg_accessor[target, member];
            if (src != null && trg != null)
            {
                DynamicPropertySet(src, trg);
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM