How do I create a new delegate type based on an existing one, in C#?

前端 未结 4 1523
温柔的废话
温柔的废话 2021-02-12 21:46

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 th

相关标签:
4条回答
  • 2021-02-12 22:00

    I didn't believe jon-skeet. I had to try it for myself. He was right.

    public void F(object sender, MouseEventArgs e) {}; 
    public MyLeftClickHandler l;
    public MyRightClickHandler r;
    public void Test()
    {
        l = F;  // Automatically converted.
        r = F;  // Automatically converted to a different type.
        l = r;  // Syntax error.  Incompatible types.
        l = new MyLeftClickHandler(r);  // Explicit conversion works.
    }
    

    That wasn't obvious!

    0 讨论(0)
  • 2021-02-12 22:01

    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);
    

    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?

    0 讨论(0)
  • 2021-02-12 22:02

    No. According to the C# documentation, delegate types are sealed, and you cannot create a new delegate type that inherits from an existing one.

    0 讨论(0)
  • 2021-02-12 22:12

    I you only want to achieve compile time type checking I guess it would be enough to create specialized EventArgs classes for the cases that you describe. That way you can still take advantage of the pre-defined delegates:

    class RightMouseButtonEventArgs : MouseEventArgs {}
    class LeftMouseButtonEventArgs : MouseEventArgs {}
    
    EventHandler<RightMouseButtonEventArgs>
    EventHandler<LeftMouseButtonEventArgs>
    
    0 讨论(0)
提交回复
热议问题