mercredi 21 septembre 2022

C# why can i manually set value but cant by setvalue(reflection)?

when i try to access a field and set value like asm.getField("name").setValue(obj,function); i get an error : 'Object of type 'System.Action`1[System.String]' cannot be converted to type 'ReflectionAndPlugins.Human+addToConsole'.'

There is my code below

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+"!");
    }

}

}





Aucun commentaire:

Enregistrer un commentaire