terça-feira, 15 de junho de 2010

Method extension MSDN

Aqui fica um exemplo que achei interessante sobre extensão de metodos em .net

namespace Extensions
{
using System;
using ExtensionMethodsDemo1;

// Define extension methods for any type that implements IMyInterface.
public static class Extension
{
public static void MethodA(this IMyInterface myInterface, int i)
{
Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, int i)");
}

public static void MethodA(this IMyInterface myInterface, string s)
{
Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, string s)");
}

// This method is never called, because the three classes implement MethodB.
public static void MethodB(this IMyInterface myInterface)
{
Console.WriteLine("Extension.MethodB(this IMyInterface myInterface)");
}
}
}
namespace ExtensionMethodsDemo1
{
using System;
using Extensions;

public interface IMyInterface
{
void MethodB();
}

class A : IMyInterface
{
public void MethodB(){Console.WriteLine("A.MethodB()");}
}

class B : IMyInterface
{
public void MethodB() { Console.WriteLine("B.MethodB()"); }
public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); }
}

class C : IMyInterface
{
public void MethodB() { Console.WriteLine("C.MethodB()"); }
public void MethodA(object obj) { Console.WriteLine("C.MethodA(object obj)"); }
}

class ExtMethodDemo
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
TestMethodBinding(a,b,c);
}

static void TestMethodBinding(A a, B b, C c)
{
// A has no methods, so each call resolves to
// the extension methods whose signatures match.
a.MethodA(1); // Extension.MethodA(object, int)
a.MethodA("hello"); // Extension.MethodA(object, string)
a.MethodB(); // A.MethodB()

// B itself has a method with this signature.
b.MethodA(1); // B.MethodA(int)
b.MethodB(); // B.MethodB()

// B has no matching method, but Extension does.
b.MethodA("hello"); // Extension.MethodA(object, string)

// In each case C has a matching instance method.
c.MethodA(1); // C.MethodA(object)
c.MethodA("hello"); // C.MethodA(object)
c.MethodB(); // C.MethodB()
}
}
}
/* Output:
Extension.MethodA(this IMyInterface myInterface, int i)
Extension.MethodA(this IMyInterface myInterface, string s)
A.MethodB()
B.MethodA(int i)
B.MethodB()
Extension.MethodA(this IMyInterface myInterface, string s)
C.MethodA(object obj)
C.MethodA(object obj)
C.MethodB()
*/

Sem comentários: