上次我问了个类似的问题:
http://topic.csdn.net/u/20080731/12/abedaf2c-f959-4039-ac21-d76b77fa0a98.html
已经由ojlovecd解决,在此再次感谢!但是自定义事件跟WinForm里的预定义事件在实现上有区别,上次的解决方法解决不了自定义事件的情况
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
oth.Eve += new Action(Method3);
}
void Method3()
{
MessageBox.Show("3");
}
Other oth = new Other();
private void button1_Click(object sender, EventArgs e)
{
oth.Eve -= Method3;//Method3可见,直接移除
//Other是引用的其他类库,根本不知道Eve订阅了哪些方法
}
private void button2_Click(object sender, EventArgs e)
{
oth.Begin();
}
}
class Other//此类不能修改!
{
public Other()
{
Eve += new Action(Method1);
Eve += new Action(Method2);
}
public event Action Eve;
public void Begin()
{
if (Eve != null)
Eve();
}
void Method1()
{
MessageBox.Show("1");
}
void Method2()
{
MessageBox.Show("2");
}
}如上,Other类是引用别的类库,没有源代码,不能修改
Form1是自己写的,可以任意修改在button2的单击事件中我引发了oth的Eve事件
我希望在button1的单击事件中移除Eve事件的处理方法,使得单击button2不执行任何操作
由于Method3是在Form1中定义的,所以我可以直接移除
但是Method1,Method2却不行
我用反射的方法也没有找到解决办法
http://topic.csdn.net/u/20080731/12/abedaf2c-f959-4039-ac21-d76b77fa0a98.html
已经由ojlovecd解决,在此再次感谢!但是自定义事件跟WinForm里的预定义事件在实现上有区别,上次的解决方法解决不了自定义事件的情况
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
oth.Eve += new Action(Method3);
}
void Method3()
{
MessageBox.Show("3");
}
Other oth = new Other();
private void button1_Click(object sender, EventArgs e)
{
oth.Eve -= Method3;//Method3可见,直接移除
//Other是引用的其他类库,根本不知道Eve订阅了哪些方法
}
private void button2_Click(object sender, EventArgs e)
{
oth.Begin();
}
}
class Other//此类不能修改!
{
public Other()
{
Eve += new Action(Method1);
Eve += new Action(Method2);
}
public event Action Eve;
public void Begin()
{
if (Eve != null)
Eve();
}
void Method1()
{
MessageBox.Show("1");
}
void Method2()
{
MessageBox.Show("2");
}
}如上,Other类是引用别的类库,没有源代码,不能修改
Form1是自己写的,可以任意修改在button2的单击事件中我引发了oth的Eve事件
我希望在button1的单击事件中移除Eve事件的处理方法,使得单击button2不执行任何操作
由于Method3是在Form1中定义的,所以我可以直接移除
但是Method1,Method2却不行
我用反射的方法也没有找到解决办法
{
EventInfo ei = oth.GetType().GetEvent("Eve");
FieldInfo fi = oth.GetType().GetField("Eve", BindingFlags.NonPublic | BindingFlags.Instance);
Action act = (Action)fi.GetValue(oth);
ei.RemoveEventHandler(oth, act);
//oth.Eve -= Method3;
}这100分咋办?要不还是给ojlovecd?