开发者

Defining C# events without an external delegate definition

just out of curiosity: is it possible to define e开发者_StackOverflow中文版vents in C# without defining a delegate type beforhand?

something like public event (delegate void(int)) EventName


There's built in generic delegate types, Action<> and Func<>, where Action returns void. Each generic type argument is type type of the argument to be passed to the delegate. e.g.

public event Action<int> EventName;

Also, there's a generic EventHandler<T> to follow the convention of passing the Object sender, and having an EventArgs type.


No, it is not possible; ECMA-334, § 17.7 states:

The type of an event declaration shall be a delegate-type (§11.2)

and § 11.2 defines:

delegate-type:
    type-name

However, since C# 3, you can use various predefined generic types such as Action<int> so that you almost don’t have to define your own delegate types.


No, AFAIK this is not possible with C#.

The reason why I think so is that a .NET event is basically a delegate with certain restrictions added. That is, the event keyword does not define a new type; conceptually speaking, it's more like a modifier (think things such as private or readonly), which is used in a declaration to modify an already existing delegate type. It's this modification that adds the restrictions:

public EventHandler x;

This is a normal delegate that can be passed around (copied) and invoked by anyone.

public event EventHandler x;

Under the hood, this is also a normal delegate, but it can only be set (=) and invoked by the type containing x; further, the delegate cannot be passed to third parties; these can only perform the add (+=) and remove (-=) operations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜