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!