Better way to call overloaded functions with more-derived parameters, passing in less-derived types

后端 未结 2 1639
予麋鹿
予麋鹿 2021-01-28 09:58

I have 16 methods that take two parameters, and each of the two parameters can be either an \'Insertion\' or a \'Deletion\', both of which implement IFragment. I also have four

2条回答
  •  抹茶落季
    2021-01-28 10:23

    I've implemented DynamicDispatcher.cs which fulfills this need.

    It uses reflection and a stack trace (a single one on construction) to generate a tree of overloads by parameter types. It handles bidirectional casting on base classes and implemented interfaces.

    Since it's part of a larger project and doesn't have any documentation, here's an example use (from the same project):

        public static void DeleteTreeNodeChild(BehaviorTree.Choice parentNode, BehaviorTree.Node childNode) {
            parentNode.Children.Remove(childNode);
        }
    
        public static void DeleteTreeNodeChild(BehaviorTree.Optional parentNode, BehaviorTree.Node childNode) {
            Debug.Assert(parentNode.Child == childNode);
            parentNode.Child = null;
        }
    
        public static void DeleteTreeNodeChild(BehaviorTree.Repetition parentNode, BehaviorTree.Node childNode) {
            Debug.Assert(parentNode.Child == childNode);
            parentNode.Child = null;
        }
    
        public static void DeleteTreeNodeChild(BehaviorTree.Sequence parentNode, BehaviorTree.Node childNode) {
            parentNode.Children.Remove(childNode);
        }
    
        private static DynamicDispatcher _deleteTreeNodeChildDynamicDispatcher;
        public static void DeleteTreeNodeChild(BehaviorTree.Node parentNode, BehaviorTree.Node childNode) {
            if (_deleteTreeNodeChildDynamicDispatcher == null) {
                _deleteTreeNodeChildDynamicDispatcher = new DynamicDispatcher();
            }
            _deleteTreeNodeChildDynamicDispatcher.Dispatch(null, parentNode, childNode);
        }
    
        

    提交回复
    热议问题