Using 'dynamic' in C# to implement Visitor Pattern

前端 未结 2 1343
刺人心
刺人心 2021-01-04 09:36

I have an application where I am performing an operation on a series of elements and the exact nature of the operation depends on the type of the element being operated upon

2条回答
  •  佛祖请我去吃肉
    2021-01-04 10:02

    Yes, I was considering this approach, but decided against it for a more traditional approach. I derive each visitor from an interface that has Visit methods for each type I want to implement the operation for.

    If you have a number of different operations you want to implement as visitors, eg. Save and Load operations, and you might want to add more in the future; with the dynamic approach you don't get compilation errors if you forget to implement your operation for one of the types you need to handle. You'll only find out when the program crashes and burns at runtime.

    I want to be sure at compile time that any operation has been implemented for all of the possible types.

提交回复
热议问题