相关疑难解决方法(0)

为什么我们不能用访问器引发事件?

为什么我们不能使用自定义实现来引发事件,而没有它们可以实现?看到这段代码:

public class Program
{
    private EventHandler myEvent;
    public event EventHandler MyEvent
    {
        add { myEvent += value; }
        remove { myEvent -= value; }
    }

    public event EventHandler AnotherEvent;

    public static void Main()
    {
        var target = new Program();
        target.MyEvent(null, null);       // ERROR CS0079
        target.AnotherEvent(null, null);  // compiles
    }
}
Run Code Online (Sandbox Code Playgroud)

你看到我的班级都宣布了这两个事件.虽然target.AnotherEvent(...)编译得很好,target.MyEvent(...)但不是:

Event MyEvent只能出现在+ =或 - =的左侧.

我知道一个事件只是一个带有add-and-remove方法的委托.因此AnotherEvent编译器将其转换为add-and-remove-method:

private EventHandler _AnotherEvent;
public event EventHandler AnotherEvent
{ 
    add { _AnotherEvent += value; }
    remove { …
Run Code Online (Sandbox Code Playgroud)

c# events

6
推荐指数
1
解决办法
163
查看次数

C#中的内部类

直到最近,我还没有说过普通类和内部类/子类之间存在差异.

内部类的实例与其包含类的实例之间的关系是什么,内部类的目的/使它们与众不同的目的是什么?

c# nested-class

4
推荐指数
2
解决办法
2615
查看次数

标签 统计

c# ×2

events ×1

nested-class ×1