gpt4 book ai didi

c# - 使用反射从类型成员调用方法

转载 作者:行者123 更新时间:2023-11-30 20:54:57 24 4
gpt4 key购买 nike

我有一个 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);
}

最佳答案

你把它倒过来了。 InvokeMethodInfo上的一个方法,所以你需要调用method变量上的Invoke方法。应该是:

Object result = method.Invoke(item);

关于c# - 使用反射从类型成员调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18662646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com