为了账号安全,请及时绑定邮箱和手机立即绑定

您好,请问C# 怎样用反射创建的对象的给成员委托实例注册方法?

您好,请问C# 怎样用反射创建的对象的给成员委托实例注册方法?

HUH函数 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);用反射动态创建FrmLog 对象,怎样给FrmLog委托实例注册方法?
查看完整描述

2 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

将反射创建的对象赋值给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));
}

查看完整回答
反对 回复 2021-11-23
?
四季花海

TA贡献1811条经验 获得超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实现IMyForm接口,然后获取实例后强转为接口对象就可以了



查看完整回答
反对 回复 2021-11-23
  • 2 回答
  • 0 关注
  • 393 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信