如何创建基于现有一个新的委托类型

如何创建基于现有一个新的委托类型

本文介绍了如何创建基于现有一个新的委托类型,在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法,我可以创建基于现有一个新的委托类型的任何方式?就我而言,我想创建一个委托 MyMouseEventDelegate 这将具有相同的功能事件处理程序和LT; MouseEventArgs>

Is there any way that I can create a new delegate type based on an existing one? In my case, I'd like to create a delegate MyMouseEventDelegate which would have the same functionality as EventHandler<MouseEventArgs>.

为什么我要这样?趁编译时类型检查,当然!这样一来,我可以有两种不同的代表: MyRightClickHandler MyLeftClickHandler ,两者永远不得混淆 - 即使他们都是功能上等同于事件处理程序和LT; MouseEventArgs方式>

Why do I want this? To take advantage of compile-time type-checking, of course! This way, I can have two different delegates: MyRightClickHandler and MyLeftClickHandler, and never the twain shall be confused - even if they are both functionally identical to EventHandler<MouseEventArgs>.

有没有语法,做这样的事情

Is there syntax to do this sort of thing?

哦,这样的代码:

using MyRightClickHandler = EventHandler<MouseEventArgs>



不够好。它不会做任何类型检查,因为它实际上并不创建新的类型。而且我必须贴上这样一行到每一个代码文件,在其中我要提到 MyRightClickHandler

推荐答案

嗯,这是因为复制从原来的委托声明一样简单。没有什么在C#中自动执行此操作的,但我不能看到它的太大负担:

Well, it's as simple as copying the delegate declaration from the original. There's nothing in C# to do this automatically, but I can't see it's much of a burden:

public delegate void MyLeftClickHandler(object sender, MouseEventArgs e);
public delegate void MyRightClickHandler(object sender, MouseEventArgs e);



这不像 MouseEventHandler 将改变任何时间很快...

It's not like MouseEventHandler is going to change any time soon...

你有没有真正被因在错误的地方使用了错误的代表,虽然虫子咬伤?我不记得曾经有发现这个问题我自己,在我看来,你是引入更多的工作(和其他开发人员不熟悉的一套代表) - ?你肯定是值得的。

Have you actually been bitten by bugs due to using the wrong delegates in the wrong places though? I can't remember ever having found this a problem myself, and it seems to me you're introducing more work (and an unfamiliar set of delegates for other developers) - are you sure it's worth it?

这篇关于如何创建基于现有一个新的委托类型,在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:15