module TalkMixin def say_hello puts "hello" end end class Animal def eat puts "mpf mpf mpf ..." end end class Dog < Animal include TalkMixin def bark puts "wuff wuff" end end dog = Dog.new dog.eat dog.bark dog.say_hello
Now, extension methods in C# allow us to do something similar:
public interface ITalker{} public static class TalkMixin { public static void SayHello(this ITalker animal){ Console.WriteLine("hello"); } } public class Animal { public void Eat() { Console.WriteLine("mpf mpf mpf ..."); } } public class Dog : Animal, ITalker { public void Bark() { Console.WriteLine("wuff wuff"); } } [TestFixture] public class MixinTest { [Test] public void Inerface_Mixin() { Dog dog = new Dog(); dog.Eat(); dog.Bark(); dog.SayHello(); } }Not bad... this technique is heavily used in .NET 3.5, for instance in the IEnumerable interface.
No comments:
Post a Comment