简体   繁体   English

C#内置事件

[英]C# built-in events

After reading the following piece of code : 阅读下面的代码后:

[SerializableAttribute]
public delegate void EventHandler<TEventArgs>
(
   object sender,
   TEventArgs e
)

Why did not Microsoft guys give Object type for the "e" parameter just like the sender parameter? 为什么微软的人不像发送者参数那样为“e”参数提供对象类型? am I missing something major here? 我错过了一些重要的东西吗?

If they had done that, people would constantly have to cast the args parameter. 如果他们这样做了,人们就会经常抛出args参数。 The point is that you can do things like: 关键是你可以做以下事情:

public event EventHandler<SomeInterestingEventArgs> SomeEvent;

and: 和:

obj.SomeEvent += (sender, args) => Console.WriteLine(args.SomeSpecificProperty);

This is a convenient way of replacing the need to declare: 这是替换声明需求的便捷方式:

public delegate void SomeInterestingEventHandler(
    object sender, SomeInterestingEventArgs args);

which is what you would have to do without this. 没有这个你就不得不这样做。

You can make your own event args class that has some useful properties on it. 您可以创建自己的事件args类,其中包含一些有用的属性。 Like the mouse click event args (can't remember the proper name) has an X and Y prop to tell you what point was clicked. 就像鼠标点击事件args(不记得正确的名称)有一个X和Y道具来告诉你点击了什么点。 Thanks to generics you don't need the casting you would with just a plain old object. 多亏了泛型,你不需要使用普通旧物体进行铸造。 You'd just have 你有

MyEventHandler<MouseClickedEventArgs>(object sender, MouseClickedEventArgs e). 

And everything is strongly typed 一切都是强类型的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM