2

我向一个事件添加了一个方法,但现在想在某些条件下从这些事件上删除该方法:

public MyClassConstructor()
{
    otherClassObj.OnMyDataReceived += new EventHandler(analyzeValues);
}
private void analyzeValues(object sender, EventArgs e)
{
    // finished analysis
    otherClassObj.OnMyDataReceived -= analyzeValues;
}

这似乎使程序崩溃,但我不明白为什么。这是我的第一个 C# 程序。谢谢。

4

3 回答 3

2

也许您的问题是您举办活动的方式?您必须首先将事件背后的当前委托复制到一个局部变量,然后检查它是否为空,然后才调用它。像这样:

var omdr = OnMyDataReceived;
if (omdr != null)
    omdr(this, new EventArgs());
于 2013-04-12T18:40:11.720 回答
2

确保您的事件访问器编写得当。它应该看起来像这样:

private EventHandler onMyDataReceived;
public event EventHandler OnMyDataReceived
{
    add
    {
        lock (OnMyDataReceived)
        {
            onMyDataReceived += value;
        }
    }
    remove
    {
        lock (OnMyDataReceived)
        {
            onMyDataReceived -= value;
        }
    }
}

另外,考虑使用它来添加事件处理程序:

otherClassObj.OnMyDataReceived += analyzeValues;
于 2013-04-12T18:27:32.533 回答
1

以下应用程序演示了如何订阅和取消订阅事件。您可以将此代码放在新的控制台应用程序中以运行它。

它表明第一次引发事件时,会调用您的事件处理程序,然后自行取消订阅。第二次,不再订阅任何处理程序,也没有任何反应。

using System;
class Program
{

    static void Main(string[] args)
    {
        MyClass c = new MyClass();
        Console.WriteLine("Ready..");
        Console.ReadLine();
    }
}

public class MyClass
{
    OtherClass otherClassObj = new OtherClass();

    public MyClass()
    {
        Console.WriteLine("Class constructor.. adding event");
        otherClassObj.OnMyDataReceived += analyzeValues;

        Console.WriteLine("Raising event 1");
        otherClassObj.Raise();

        Console.WriteLine("Raising event 2");
        otherClassObj.Raise();
    }

    private void analyzeValues(object sender, EventArgs e)
    {
        Console.WriteLine("Event handler");
        Console.WriteLine("Removing event");
        otherClassObj.OnMyDataReceived -= analyzeValues;
    }
}

public class OtherClass
{
    public event EventHandler OnMyDataReceived;

    public void Raise()
    {
        if (OnMyDataReceived != null)
        {
            OnMyDataReceived(this, EventArgs.Empty);
        }
    }
}
于 2013-04-12T18:33:01.903 回答