String- Function dictionary c# where functions have different arguments

后端 未结 9 3179
温柔的废话
温柔的废话 2021-02-19 09:13

Basically I\'m trying to make a string to function dictionary in c#, I\'ve seen it done like this:

Dictionary>
<         


        
9条回答
  •  感情败类
    2021-02-19 09:44

    There are a few ways to accomplish this, but there is a reason there are no good answers. If you were able to do this you would still need more logic around calling the functions, unless your functions were to only have differing numbers of strings. Then each function could do it's own handling of the arguments.

    With that said you could do this:

        public delegate string DelegateAction(params string[] args);
        public Dictionary Actions = new Dictionary();
    
        public void InitializeDictionary()
        {
          Actions.Add("walk",Move);
        }
    
    
        public string Move(params string[] args)
        {
          if (args.Length > 0)
          {
            if (!string.IsNullOrWhiteSpace(args[0]))
            {
              switch (args[0].ToLower())
              {
                case "forward":
                  return "You move forward at a leisurely pace";
                case "right":
                case "left":
                case "backward":
                  throw new NotImplementedException("Still need to set these up");
                default:
                  return "You need to specify a valid direction (forward,backward,right,left).";
              }
            }
          }
          return "You need to specify a direction.";
        }
    
        public string ProcessAction(string action, params string[] args)
        {
          return Actions[action.ToLower()].Invoke(args);
        }
    

    Let it be said, if you are going to do this, keys are case sensitive so you will need to use either lowercase/ToLower() or UPPERCASE/ToUpper() for them. You can handle your other parameters many ways, some which you can use other case insensitive matching, but with the switch-case in this example the cases must match also.

    Good Luck!

提交回复
热议问题