0

I have:

  • a name of a class field
  • the class instance that contains the field

The class field 'may' be:

  • a field I would like to set directly through reflection
  • a List instance which I would NOT like to set as I don't want to assign a new List instance to it, but instead would like to add to using the 'Add' method.

The problem: I don't have the actual object of the List instance inside the containing object.

Some sample code to illustrate the problem:

class Target
{
    FieldInfo m_FieldInfo;
    MethodInfo m_MethodInfo;
    object m_Target;

    public Target( string nameOfTargetField, object containingObject )
    {
        m_Target = containingObject;
        Type type = containingObject.GetType();
        BindingFlags bindingFlag = BindingFlags.Public | BindingFlags.Instance;
        m_FieldInfo = type.GetField( nameOfTargetField, bindingFlag );

        type = m_FieldInfo.FieldType;
        m_MethodInfo = type.GetMethod( "Add" );
    }

    public void Set( object value )
    {
        if (m_MethodInfo != null) {
            object[] parametersArray = new object[] { value };
            // This obviously will not work, as m_Target is the containing object,
            // no the List<T> instance contained within it:
            m_MethodInfo.Invoke( m_Target, parametersArray );
        } else if (m_FieldInfo != null) {
            m_FieldInfo.SetValue( m_Target, value );
        }
    }
}

Any suggestions?

Thanks!

Jake1164
  • 12,291
  • 6
  • 47
  • 64
Christian
  • 11
  • 2
  • What about [`FieldInfo.GetValue`](http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.getvalue.aspx)? If you have any particular problems using that `GetValue` method (as opposed to simply not happening to find it/look for the right name - happens to me all the time :-) ), let me know and I'll post some sample code. – O. R. Mapper Jun 28 '12 at 11:58
  • Yes, of course ... Kind of obvious... ;-) – Christian Jun 28 '12 at 12:28
  • this worked for me http://stackoverflow.com/a/9235316/74585 – Matthew Lock Mar 17 '15 at 03:01

0 Answers0