سؤال

I have a class Person which contains a field for the person's mother and the person's father. I want to call a method called "WriteName" from the members of the person Instance.

How can I do that with reflection?

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
        }


    }

I would like to have this output:

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

EDIT:

Th correct code after my changes is:

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);
    }
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

adding to Reed Copsey's answer i dont think you can have item as a parameter to Invoke.

The Invoke method takes in 2 parameters, first the object on which the method should be invoked and second the parameters for the method.

so the 1st parameter should be of type Person (since the method invoked is defined for Person class) and the 2nd parameter should be null (since the method does not take any parameters)

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

i hope the above code will give your required output

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top