第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

您好,請問C# 怎樣用反射創(chuàng)建的對象的給成員委托實例注冊方法?

您好,請問C# 怎樣用反射創(chuàng)建的對象的給成員委托實例注冊方法?

HUH函數(shù) 2021-11-19 11:11:26
namespace LogicForms{public delegate void SetDelegate(int iProgressValue);public partial class FrmLog : Form{//控制主窗體的進度條public SetDelegate SetProgress;}用new對象是FrmLog frmL = new FrmLog();frmLog.SetProgress += new SetDelegate(SetStatus);用反射動態(tài)創(chuàng)建FrmLog 對象,怎樣給FrmLog委托實例注冊方法?
查看完整描述

2 回答

?
寶慕林4294392

TA貢獻2021條經(jīng)驗 獲得超8個贊

將反射創(chuàng)建的對象賦值給obj。然后obj.GetType().GetField("SetProgress")獲得指定字段,再賦值。
Object obj=Assembly.Load("xx").CreateInstance("xx.FrmLog ");
FieldInfo fi = obj.GetType().GetField("SetProgress");
if (fi.IsPublic == true)
{
fi.SetValue(obj, new SetDelegate(SetStatus));
}

查看完整回答
反對 回復(fù) 2021-11-23
?
四季花海

TA貢獻1811條經(jīng)驗 獲得超5個贊

using System;
using System.Reflection;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

SetDelegate sd = null;
private void button1_Click(object sender, EventArgs e)
{
var _Assembly = Assembly.LoadFile(Application.StartupPath + "\\WindowsFormsApplication1.exe");
var _Type = _Assembly.GetType("WindowsFormsApplication1.Form2");
var _Instance = _Type.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, null);

sd += new SetDelegate(SetStatus);
sd += new SetDelegate(SetStatus2);
var _Event = _Type.GetField("SetProgress");
_Event.SetValue(_Instance, sd); // 向事件中添加方法

_Type.InvokeMember("ShowDialog", BindingFlags.InvokeMethod, null, _Instance, null); // 顯示窗體2

}

private void SetStatus(MyProgress _MyProgress)
{
_MyProgress.iProgressValue = 3;
}

private void SetStatus2(MyProgress _MyProgress)
{
_MyProgress.iProgressValue = 42;
}
}
}

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public SetDelegate SetProgress;
public Form2()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
MyProgress mp = new MyProgress();
mp.iProgressValue = 0;
SetProgress(mp);
MessageBox.Show(mp.iProgressValue.ToString());
}
}
public delegate void SetDelegate(MyProgress iProgressValue);

public class MyProgress
{
public int iProgressValue = 0;
}

}

差不多就這樣,找到form2中定義的屬性。
或者采用接口的方式,讓Form2實現(xiàn)IMyForm接口,然后獲取實例后強轉(zhuǎn)為接口對象就可以了



查看完整回答
反對 回復(fù) 2021-11-23
  • 2 回答
  • 0 關(guān)注
  • 507 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號