反射:在静态字段内调用方法

时间:2016-08-30 03:50:40

标签: c# reflection system.reflection

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

在dll中

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

但我收到了错误

未处理的类型' System.Reflection.TargetException'发生在mscorlib.dll中     附加信息:对象与目标类型不匹配。

然后如何调用它? 三江源。

2 个答案:

答案 0 :(得分:1)

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!

答案 1 :(得分:0)

Once you get the FieldInfo of name_b, you need to call FieldInfo.GetValue(null) to get the actual value (the instance of class_b). You also need the MethodInfo of typeof(class_b).method.

Once you have both of those, you can call methodInfo.Invoke passing in the instance of class_b.