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

Time:09-27

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

CodePudding user response:

You need to help the compiler by explicitly casting the method Form1.addToConsole to Human.addToConsole delegate:

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

or you can change the declaration of Human.func field to

public Action<string> func;
  • Related