在静态类中委托

时间:2017-02-07 11:33:48

标签: c# static delegates

为了没有为每个表格实现一个新课程的义务,我希望将它保持静态。 我的问题是它是一个重新组合所有签名函数的类,它定义了我的代码中使用的代理(当我需要它时的所有形式)。 由于Delegate是函数指针,我想知道如果在静态类中声明委托是可行的,我的意思是它有效,我试过但是我想知道它是否存在已知问题。 这是代码:

 public static class DEL_Prototype
    {
        public delegate void DEL_delegate1(Double AValue);
    } 

我称之为:

 DEL_Prototype.DEL_delegate1 += new DEL_delegate1(myfunctiontopoint);

编辑:这是更广泛的委托使用(例如,一个调试器,以了解每个委托附加多少订阅者或包含所有委托使用的任何其他内容) 代码

   public partial class Form1 : Form
    {
        private DEL_Prototype.DEL_delegate1 m_SetValueCbk;
        private Form2 FormwithLabel;
        public Form1()
        {
            InitializeComponent();         
            FormwithLabel = new Form2(this);
            FormwithLabel.Show();
        }
        public event DEL_Prototype.DEL_delegate1 SetValueCbk
        {
            add { m_SetValueCbk += value; DEL_Prototype.InvokationListChanged(1, m_SetValueCbk); }
            remove { m_SetValueCbk -= value; DEL_Prototype.InvokationListChanged(-1, m_SetValueCbk); }
        }
    }

窗体2

public partial class Form2 : Form
{
    private Form1 ThisForm1;
    public Form2() { }
    public Form2(Form1 Form1link)
        : this()
    {
        ThisForm1 = Form1link;
        InitializeComponent();
    }
    protected void SetValueCbkFN(Double value)
    {            ;        }
    private void button1_Click(object sender, EventArgs e)
    {
        ThisForm1.SetValueCbk += new DEL_Prototype.DEL_delegate1(this.SetValueCbkFN);
    }
    private void button2_Click(object sender, EventArgs e)
    {
        ThisForm1.SetValueCbk -= new DEL_Prototype.DEL_delegate1(this.SetValueCbkFN);
    }
}
public static class DEL_Prototype
{
    public delegate void DEL_delegate1(Double AValue);

    public static void InvokationListChanged(int dir, Delegate Name)
    {
        string msg = dir < 0 ? "Someone unsubscribed from the event" : "Someone subscribed to the event";
        if (Form1.ActiveForm.InvokeRequired)//thread safe implementation
        {//if control created in the same thread that label1 its else otherwise invoke method the change text asynchronously
            msg = string.Concat(msg + " subscribe number: " + "0");
            Form1.ActiveForm.Invoke(new MethodInvoker(() => { MessageBox.Show(msg); }));
        }
        else
        {
            if (Name != null) msg = string.Concat(msg + " subscribe number: " + Name.GetInvocationList().Count().ToString());
            else msg = string.Concat(msg + " subscribe number: " + "0");
            MessageBox.Show(msg);
        }
    }
} 

是否有感觉?

非常感谢。

0 个答案:

没有答案