当我试图访问一个字段并设置类似asm.getField(“name”).setValue(obj,function)值时;我得到一个错误:'无法将类型为'System.Action '1[System.String]'的对象转换为类型'ReflectionAndPlugins.Human+ addToConsole'。'
下面是我的代码
using System.Reflection;
namespace ReflectionAndPlugins
{
public partial class Form1 : Form
{
delegate void rundel();
delegate void DaddToConsole(string txt);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Assembly asm = Assembly.GetExecutingAssembly();
foreach (Type item in asm.GetTypes())
{
if(item.Name == "Human")
{
object ahmet = Activator.CreateInstance(item);
((Human)ahmet).func = addToConsole; // WORKS
// item.GetField("func").SetValue(ahmet, addToConsole); DOENST WORK ?
item.GetField("name").SetValue(ahmet, "ahmet");
object[] param = { "Ali" };
item.GetMethod("greet").Invoke(ahmet, param);
}
}
}
void addToConsole(string txt)
{
textBox1.AppendText(txt);
textBox1.AppendText(Environment.NewLine);
}
}
public class Human
{
public string name;
public delegate void addToConsole(string txt);
public addToConsole func;
public void greet(string who)
{
func("Hi "+who+", im "+name+"!");
}
}
}
1条答案
按热度按时间n6lpvg4x1#
您需要将Form1.addToConsole方法显式转换为Human.addToConsole委托,以帮助编译器:
也可以将Human.func字段的声明更改为