using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibrary
{
public sealed class SealedClass
{
}
public static class Extension
{
public const string sex="male";
public static string Foo(this SealedClass s, string a)
{
return "zbo";
}
}
}
作用,对不能改的代码做扩展,比方说第三方的代码,系统的String类,等等。
绑定的顺序,先找有没有实例的实现,没有的话才回去找扩展的实现。
msdn:You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx