方法原型:public void EditingPart(XElement xml, System.Windows.Forms.FormClosedEventHandler end) 但是使用时编译通不过:_Hooks.EditingPart(pt.Parameter,dlg.FormClosed);说事件智能+=或-=使用dlg是Winform 请问我想在方法内给事件绑定委托该如何做?

解决方案 »

  1.   

    使用委托加事件可以解决
    public class a
    {
       public delegate void add(int a,int b);
       public event add onadd;
       public void run()
      {
       onadd(1,2)//这里触发事件
      }
    }public class b
    {
     a obj=new a();
     a.onadd+=new onadd(add2);
     public void add2(int a ,int b)
     {
      MessageBox.Show((a+b).ToString());
     }
     a.run();//触发事件将会调用你传进去的方法add2
    }
      

  2.   

    using System;
    using System.Windows.Forms;namespace WindowsFormsApplication4
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        public void EditingPart(string xml, System.Windows.Forms.FormClosedEventHandler end)
            {
                Console.WriteLine(xml);
                if (end != null)
                {
                    end(this,new FormClosedEventArgs(CloseReason.FormOwnerClosing));
                }
            }
            private void button1_Click(object sender, EventArgs e)
            {
                EditingPart("ddd",this.Form1_FormClosed);
            }        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
            {
                Console.WriteLine("e.CloseReason" + e.CloseReason);
            }
        }
    }
    输出结果:ddd
    e.CloseReasonFormOwnerClosing
      

  3.   

    Forms.FormClosed先+=添加委托方法new Forms.FormClosedEventHandler(onformclosed),然后再_Hooks.EditingPart(pt.Parameter,onformclosed);
      

  4.   


    事件是一种安全的使用委托的方法,防止有人修改、随意触发事件。只有对象自己才可以触发自己的事件。要强行触发其它对象自己的事件,那么你需要在你的end参数传递触发事件的对象,并且反射来触发事件。
      

  5.   

    事件的本质是属性,一种特殊的属性,具有add/remove函数的属性,具有+=,-=操作符重载的特殊属性。属性不是类型,所以不能用于声明变量,但委托可以。-----------------------------------[your]
    public void EditingPart(XElement xml, System.Windows.Forms.FormClosedEventHandler end)
    [answer]
    这个声明还是挺好的
     
    [your]
    但是使用时编译通不过:
    _Hooks.EditingPart(pt.Parameter,dlg.FormClosed);
    [answer]
    这样不行,因为事件本身是属性,返回值可能是null,你可以尝试获取事件的绑定函数,然后调用,例如:例如,这样来获取列表private void Form6_Load(object sender, EventArgs e)
    {
        TestPT pt = new TestPT();
        Form6 _Hooks = new Form6();
        Form dlg = new Form();
        dlg.FormClosed += delegate { MessageBox.Show("Test"); };
        FieldInfo fi = dlg.GetType().GetField("FormClosed", BindingFlags.Instance | BindingFlags.NonPublic);
        FormClosedEventHandler del = fi.GetValue(dlg) as FormClosedEventHandler;
        _Hooks.EditingPart(pt.Parameter, del);
    }public void EditingPart(XElement xml, System.Windows.Forms.FormClosedEventHandler end)
    { }public class TestPT
    {
        public XElement Parameter = new XElement("",null);
    }