2

我有一个 Person 类,其中包含该人的母亲和该人的父亲的字段。我想从人员实例的成员中调用一个名为“WriteName”的方法。

我怎样才能通过反射做到这一点?

Person child = new Person {name = "Child"} ; // Creating a person
child.father = new Person {name = "Father"}; // Creating a mother for the person
child.mother = new Person { name = "Mother" }; // Creating a father for the person
child.ExecuteReflection();

public class Person
{
    public int ID { get; set; }
    public string name { get; set; }
    public Person mother { get; set; }
    public Person father { get; set; }

    public void WriteName()
    {
        Console.WriteLine("My Name is {0}", this.name);
    }

    public void ExecuteReflection()
    {
        // Getting all members from Person that have a method called "WriteName"
        var items = this.GetType().GetMembers(BindingFlags.Instance | BindingFlags.NonPublic)
                        .Where(t => t.DeclaringType.Equals(typeof(Person)))
                        .Where(p => p.DeclaringType.GetMethod("WriteName") != null);



        foreach (var item in items)
        {
            MethodInfo method = item.DeclaringType.GetMethod("WriteName"); // Getting the method by name
            // Object result = item.Invoke(method); // trying to invoke the method, wont compile
        }


    }

我想要这个输出:

"My name is mother"
"My Name is father"

编辑:

我更改后的正确代码是:

var items = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic)
                        .Where(t => t.FieldType.Equals(typeof(Person)))
                        .Where(p => p.FieldType.GetMethod("WriteName") != null);



    foreach (var item in items)
    {
        MethodInfo method = item.DeclaringType.GetMethod("WriteName"); 
        Object result = method.Invoke((Person)item.GetValue(this), null);
    }
4

2 回答 2

3

You have it backwards. Invoke is a method on MethodInfo, so you need to call the Invoke method on the method variable. It should be:

Object result = method.Invoke(item);
于 2013-09-06T16:47:31.110 回答
1

添加到 Reed Copsey 的答案中,我认为您不能将 item 作为 Invoke 的参数。

Invoke 方法接受 2 个参数,第一个是应该调用该方法的对象,第二个是该方法的参数。

所以第一个参数应该是 Person 类型(因为调用的方法是为 Person 类定义的),第二个参数应该是 null (因为该方法不带任何参数)

Object result=method.Invoke(this,null);

我希望上面的代码会给你所需的输出

于 2013-09-06T17:03:24.897 回答