Why can a .NET delegate not be declared static?

后端 未结 6 2212
伪装坚强ぢ
伪装坚强ぢ 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:33

    Delegate declaration is actually a type declaration. It cannot be static, just like you cannot define a static enum or structure.

    However, I would rather use an interface instead of raw delegate.

    Consider this:

    public interface IGameStrategy {
        void Move(Actor actor, MoveDirection direction);
    }
    
    public class ConsoleGameStrategy : IGameStrategy {
        public void Move(Actor actor, MoveDirection direction)
        {
            // basic console implementation
            Console.WriteLine("{0} moved {1}", actor.Name, direction);
        }
    }
    
    public class Actor {
        private IGameStrategy strategy; // hold a reference to strategy
    
        public string Name { get; set; }    
    
        public Actor(IGameStrategy strategy)
        {
            this.strategy = strategy;
        }
    
        public void RunForrestRun()
        {
            // whenever I want to move this actor, I may call strategy.Move() method
    
            for (int i = 0; i < 10; i++)
                strategy.Move(this, MoveDirection.Forward);
        }
    }
    

    In your calling code:

    var strategy = new ConsoleGameStrategy();
    
    // when creating Actors, specify the strategy you want to use
    var actor = new Actor(strategy) { Name = "Forrest Gump" };
    actor.RunForrestRun(); // will write to console
    

    This similar in spirit to Strategy design pattern and allows you to decouple Actor movement from the actual implementation strategy (console, graphic, whatever). Other strategy methods may later be required which makes it a better choice than a delegate.

    Finally, you can use an Inversion of Control framework to automatically inject correct strategy instance in your Actor classes so there is no need for manual initialization.

提交回复
热议问题