Why can a .NET delegate not be declared static?

后端 未结 6 2173
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 19:42

When I try to compile the following:

public static delegate void MoveDelegate (Actor sender, MoveDirection args);

I receive, as an error: \

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 20:23

    A delegate declaration basically declares a method signature, which only includes information about its parameters and return type. And since the same delegate can point to both static and instance methods, it doesn't make sense to make the method signature itself static or instance.

    Once you have declared your delegate as:

    public delegate void MoveDelegate (Actor sender, MoveDirection args);
    

    it means that any delegate of this type must point to a method which accepts one Actor parameter, one MoveDirection parameter, and returns void, regardless of whether the method is static or instance. You can declare the delegate at namespace scope, or inside a class (just like you would declare a nested class).

    So after declaring the MoveDelegate somewhere, you can the create fields and variables of that type:

    private MoveDelegate _myMoveDelegate;
    

    and remember that the method should have a matching signature:

    // parameters and return type must match!
    public void Move(Actor actor, MoveDirection moveDir)
    {
        ProcessMove (moveDir);
    }
    
    public static void MoveStatic(Actor actor, MoveDirection moveDir)
    {
        ProcessMove (moveDir);
    }
    

    then you can assign this method to a delegate at some other place:

    private void SomeOtherMethod()
    {
         // get a reference to the Move method
         _myMoveDelegate = Move;
    
         // or, alternatively the longer version:
         // _myMoveDelegate = new MoveDelegate(Move);
    
         // works for static methods too
         _myMoveDelegate = MoveStatic;
    
         // and then simply call the Move method indirectly
         _myMoveDelegate(someActor, someDirection);
    }
    

    It is useful to know that .NET (starting from version v3.5) provides some predefined generic delegates (Action and Func) which can be used instead of declaring your own delegates:

    // you can simply use the Action delegate to declare the
    // method which accepts these same parameters
    private Action _myMoveDelegate;
    

    Using those delegates is IMHO more readable, since you can immediately identify parameters' signature from looking at the delegate itself (while in your case one needs to look for the declaration).

提交回复
热议问题