C# Extension Method 扩展方法

扩展方法是C# 3.0的新特性。它为现有的类型添加方法,从而解决了使用继承扩展所带来的所有弊端。

Demo 1 简单的扩展方法

using System;

namespace ExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = null;
            Console.WriteLine("字符串str为空字符串: " + s.AddMethod_IsNull());
            Console.WriteLine("字符串str长度: " + s.AddMethod_Length());
            Console.Read();
        }
    }

    //在静态类中定义扩展方法
    static class NullExten
    {
        //为string类型定义扩展方法AddMethod_IsNull。
        public static bool AddMethod_IsNull(this string str)
        {
            return null == str;
        }

        //为string类型定义扩展方法AddMethod_Length
        public static int AddMethod_Length(this string str)
        {
            if(str!=null)
            {
                return str.Length;
            }
            else
            {
                return 0;
            }
           
        }
    }
}

Demo 2 扩展方法的调用顺序

using System;

namespace ExtensionMethodSequence
{
    using AnotherNameSpace;
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person() { Name = "Daniel" };
            p.Print();//无参,调用本命名空间
            p.Print("Hello");//一个参数,调用另一命名空间。
            Console.Read();
        }
    }

    public class Person
    {
        public string Name { get; set; }
    }

    public static class ExtensionClass
    {
        //ExtensionMethodSequence 命名空间下的只带一个参数的扩展方法,相当于无参
        public static void Print(this Person per)
        {
            Console.WriteLine("调用当前命名空间下的扩展方法,姓名为:{0}", per.Name);
        }
    }

}

namespace AnotherNameSpace
{
    //引用
    using ExtensionMethodSequence;
    public static class ExtensionClass1
    {
        //AnotherNameSpace 命名空间下的只带一个参数的扩展方法
        public static void Print(this Person per, string s)//using ExtensionMethodSequence使Person有意义
        {
            Console.WriteLine("调用另一命名空间下的扩展方法,姓名为:{0},增加参数:{1}", per.Name,s);
        }

        public static void Print(this Person per)
        {
            Console.WriteLine("调用另一命名空间下的扩展方法,姓名为:{0}", per.Name);
        }
    }
    
}