人の母親と人の父親のフィールドを含むクラス Person があります。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);
}