winforms C#为什么我可以手动设置值,但不能通过setvalue(反射)?

dddzy1tm  于 2022-11-17  发布在  C#
关注(0)|答案(1)|浏览(145)

当我试图访问一个字段并设置类似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+"!");
        }
    }
}
n6lpvg4x

n6lpvg4x1#

您需要将Form1.addToConsole方法显式转换为Human.addToConsole委托,以帮助编译器:

item.GetField("func").SetValue(ahmet, (Human.addToConsole)addToConsole);

也可以将Human.func字段的声明更改为

public Action<string> func;

相关问题