如何使用反射修改集合中的特定项目

时间:2013-09-24 19:47:35

标签: c# reflection

我需要使用反射修改集合中的项目 - 我正在使用反射,因为直到运行时我才知道泛型集合的确切类型。

我知道如何使用SetValue()方法设置通过集合检索的属性的值,但是我可以使用SetValue()在集合中设置实际对象吗?

IEnumerable businessObjectCollection = businessObject as IEnumerable;

foreach (Object o in businessObjectCollection)
{
    // I want to set the "o" here to some replacement object in the collection if
    // a property on the object equals something
    Type t = o.GetType();
    PropertyInfo identifierProperty = o.GetType().GetProperty("Identifier");
    long entityID = (long)identifierProperty.GetValue(o, null);


    if (replacementEntity.Identifier == entityID)
    {
        // IN THIS CASE: set "o" to be the replacementEntity object
        // defined somewhere else. 

        // I can retrieve the object itself using this code, but
        // would I set the object with SetValue?
        object item = businessObjectCollection.GetType().GetMethod("get_Item").Invoke(businessObjectCollection, new object[] { 1 });                              
    }

}

4 个答案:

答案 0 :(得分:2)

collection.GetType().GetProperty("Item").SetValue(collection, o, new object[] { 1 })

答案 1 :(得分:1)

您可以将其替换为执行替换内联的新枚举,而不是尝试修改可枚举。这真的取决于你之后做了什么,尽管如此YMMV。

IEnumerable newCollection = businessObjectCollection.Cast<object>().Select((o) =>
{
    Type t = o.GetType();
    PropertyInfo identifierProperty = o.GetType().GetProperty("Identifier");
    long entityID = (long)identifierProperty.GetValue(o, null);

    if (replacementEntity.Identifier == entityID)
    {
        return replacementEntity;
    }
    return o;
});

答案 2 :(得分:0)

好吧,您使用get_Item检索它,以便您可以致电set_Item进行设置:

businessObjectCollection.GetType().GetMethod("set_Item").Invoke(businessObjectCollection, new object[] { 1, replacementEntity });

请注意,如果集合不是支持索引访问的类型,则会爆炸。

答案 3 :(得分:0)

此方法将对象添加到对象上所述对象的集合属性中。

obj是包含属性Collection

的Parent对象

propertyName是Collection属性的名称

value是要添加到Collection

的对象
private object AddItemToCollectionProperty( Object obj, string propertyName, Object value )
    {
        PropertyInfo prop = obj.GetType().GetProperty( propertyName );
        if( prop != null )
        {
            try
            {
                MethodInfo addMethod = prop.PropertyType.GetMethod( "Add" );

                if(addMethod ==null)
                {
                    return obj;
                }

                addMethod.Invoke( prop.GetValue(obj), new object [] { value }  );

            }
            catch( Exception ex )
            {
                Debug.Write( $"Error setting {propertyName} Property Value: {value} Ex: {ex.Message}" );
            }
        }
        else
        {
            Debug.Write( $"{propertyName} Property not found: {value}" );
        }

        return obj;
    }
相关问题