Using 'dynamic' in C# to implement Visitor Pattern

六眼飞鱼酱① 提交于 2019-11-30 18:16:35

Are there any gotchas with the dynamic dispatching that I haven't considered? I believe this is equivalent to performing a series of if (x is TypeA) Do((TypeA)x) else..., but I could be wrong.

The main gotcha would be if a type implements more than one interface in your visitor pattern - the compiler will probably pick the one you want, but it may not be the same choice you'd make if you use if (x is TypeA)/else if (x is TypeB) logic, as you'd control the order the checks occur.

Is this actually cleaner and easier to understand than a long if/elseif method?

I personally think so. This provides a very clean, fairly decently performing dispatch determined by the runtime type, and "just works." Hard to beat simple, short, clean code. Just make sure to (potentially) handle the case where you get a runtime error from the wrong type being passed in.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!