當我嘗試訪問欄位并設定值時,例如 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 "!");
}
}
}
uj5u.com熱心網友回復:
您需要通過將 Form1.addToConsole 方法顯式轉換為 Human.addToConsole 委托來幫助編譯器:
item.GetField("func").SetValue(ahmet, (Human.addToConsole)addToConsole);
或者您可以將 Human.func 欄位的宣告更改為
public Action<string> func;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/509999.html
標籤:C#表格反射
