sealed class 做函數擴展的方法,dotnet 3.0

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章