MultiMethods for .NET
Ajai Shankar |
MultiMethods.NET is a small and fast library that implements multi-methods for .NET, and makes multi-methods available to any language that targets .NET - C#, VB.NET, JScript.NET, Managed C++ and the rest! It uses .NET dynamic assemblies (Refelection.Emit) to generate new types at runtime and dynamic IL to implement new methods at runtime. So you might want to look at the code to see how virtual methods can be intercepted at runtime using dynamic IL. It even supports .NET generic object types, ValueTypes and Arrays. Here are some examples using MultiMethods; public class One {} public class Two : One {} public class Three : Two {} public class X { [MultiMethod] public virtual void foo(One a, One b) {} protected void foo(One a, Two b) {} // method 1 protected void foo(Two a, One b) {} // method 2 } X x = (X) MultiMethods.Activator.CreateInstance(typeof(X)); x.foo(new One(), new Three()); // dispatches to method 1 x.foo(new Three(), new One()); // dispatches to method 2 public class Y { [MultiMethod] public virtual void foo(object o) {} protected void foo(int x) {} protected void foo(A a) {} protected void foo(A[] a) {} }In short, multimethods are tagged with a [MultiMethod] attribute, and objects are created using the MultiMethods.Activator class - that's all there is to it! If you want to learn more, please download MultiMethods.NET from SourceForge and try out the examples.
|
Thanks to |