2010年12月14日星期二

Extension Methods (C# Programming Guide)

Extension Methods (C# Programming Guide)
The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this is not a requirement for extension methods.
=============================================================
class ExtensionMethods2   
{
    static void Main()
    {           
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
        {
            System.Console.Write(i + " ");
        }          
    }       
}
//Output: 10 15 21 26 39 45
=============================================================
Extension methods are defined as static methods but are called by using instance method syntax.
Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
=============================================================
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }  
}

The WordCount extension method can be brought into scope with this using directive:
And it can be called from an application by using this syntax:
=============================================================
string s = "Hello Extension Methods";
int i = s.WordCount();

The following example implements an extension method named WordCount in the MyExtensions.StringExtension class
=============================================================
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
    //Extension methods must be defined in a static class
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this String str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    //Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            //  Call the method as if it were an
            //  instance method on the type. Note that the first
            //  parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}


ref: http://msdn.microsoft.com/en-us/library/bb311042.aspx

没有评论: