Search code examples
c#reflectionsystem.reflection

Reflection: invoke method inside static field


Type type_class_a = ....;
Type type_class_b = type_class_a.GetField("name_b").FieldType;
MethodInfo method = type_class_b.GetMethod("method");
method.Invoke(type_class_b,new object[] {"test_string"});

in dll

public class class_a
{
    public static class_b name_b = new class_b();
}
public class class_b
{
    public void method(string data)
    {
    }
}

but i got error

An unhandled exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll Additional information: Object does not match target type.

Then how to invoke it? Thankyou.


Solution

  • As your class class_a defines the object of type class_b and class_b contains a method named method, your approach will be as follows (in dll)

    1. Get Type of class_a object in your code (store in class_a_type variable of type Type)
    2. Get FieldInfo object of the class_a_type object for name_b object (store it in a_field_info variable of type FieldInfo)
    3. Get object of that field type (in your case, the object instance name_b) in an object by calling GetValue function of the FieldInfo object (store it in b_object variable of type object)
    4. Get MethodInfo object for the method (named method) in the above b_object object by calling b_object.GetType().GetMethod("method") (and store it in b_method object of type MethodInfo)
    5. Invoke the method by calling Invoke function on the above b_method object and passing the b_object as first parameter (the object on which to call the function) and null as second parameter (the array of parameters to be passed to the function.

    A bit confusion??? Find the example below:

    Type class_a_type = class_a_object.GetType();
    FieldInfo a_field_info = class_a_type.GetField("name_b");
    
    object b_object = a_field_info.GetValue(class_a_object);
    MethodInfo b_method = b_object.GetType().GetMethod("method");
    
    b_method.Invoke(b_object, null);
    

    Hope that helps!