65.9K
CodeProject 正在变化。 阅读更多。
Home

扩展方法(基础理解)

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.22/5 (5投票s)

2009 年 6 月 12 日

CPOL

3分钟阅读

viewsIcon

19143

downloadIcon

104

扩展方法是 C# 3.0 中的一个特性,它允许开发者在不修改、重新编译或扩展现有类的情况下,向现有类添加功能。

引言

这是 C# 3.0 中的一个新特性,有助于扩展现有类,例如无法扩展的 .NET 核心类。 你可能需要在不扩展类、重新编译现有类或修改现有方法的情况下添加功能。

关于扩展方法的几点说明

  1. 这是 C# 3.0 的一个新特性。
  2. 扩展方法允许向现有类型添加新方法。 它不需要创建派生类型、修改原始类型或重新编译原始类型。
  3. 它为程序员提供了向现有类型添加新方法的能力。
  4. 它可用于向现有的 .NET 核心类添加新方法。
  5. 它被定义为 static 方法,但使用实例方法的语法调用。
  6. 如果类型类中存在与扩展方法同名的成员方法,则成员方法将优先于扩展方法。

例如:Show 方法是 Message 类的成员方法。 因此,如果存在名为 Show 的扩展方法,则对于 Message 类型,Show 成员方法将始终优先于 Show 扩展方法。

Using the Code

扩展方法的编译器签名如下:

static class Extensions
{
    public static IEnumerable<T> Where<T>(this IEnumerable<T> sequence, 
                                          Predicate<T> predicate)
    {
        foreach (T item in sequence)
        {
            if (predicate(item))
            {
                yield return item;
            }
        }
    }
}
  1. 该方法是 static 的。
  2. 第一个参数使用修饰符 “this” 修饰。
  3. 第一个参数称为实例参数。
  4. 使用此修饰符和任何其他参数(实例参数除外)将会遇到编译时错误。
  5. this” 修饰符或实例参数不允许使用其他修饰符,例如 refout 等。
  6. 实例参数不能是指针类型。
  7. 该方法是 public 的。
  8. 实例参数不能具有类型参数的类型。 这不可能发生
    public static int Obj<T> (this T param)

扩展方法的限制

  1. 它只能访问目标类型的 public 成员。
  2. 如果扩展方法与目标类型的成员方法冲突,则始终会调用成员方法,而不是扩展方法。

扩展方法的实现和调用

  1. 定义一个 static 可见的类来包含扩展方法。
  2. 将扩展方法实现为 static 方法。
  3. 该方法的第一 个参数指定了方法所操作的类型。
  4. 第一个参数必须以 “this” 修饰符开头。
  5. 在客户端代码中,使用 using 指令添加扩展方法的命名空间。

扩展方法的示例

在第一个示例中,我将向现有的 String 类添加一个扩展方法。 此扩展方法将从 string 中删除所有元音。

使用类 extensionmethodcontainer 的修饰符 publicstatic 修改该类。

添加一个扩展方法,签名如下。 第一个参数 String 指定这是类型 String 的扩展方法。

public static String RemoveVowel(this String s)

从输入 string 中删除元音的完整代码都写在扩展方法中。

ExtensionMethodContainer.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ExtensionMethodSample 
{ 
    public static class extensionmethodcontainer 
    { 
        public static String RemoveVowel(this String s) 
        { 
            string[] vowels = new string[] { "A", "E", "I", "O", "U" }; 
            if (string.IsNullOrEmpty(s)) 
                return string.Empty; 
            List<char> chars = new List<char>(s.ToCharArray()); 
            for (int i = chars.Count - 1; i >= 0; i--) 
            { 
                for (int j = 0; j < vowels.Length; j++) 
                { 
                    if (chars[i].ToString().ToLower() == vowels[j].ToLower()) 
                        chars.RemoveAt(i); 
                } 
            } 
            return new string(chars.ToArray()); 
        } 
    } 
}

客户端代码位于 Main 类中。

main 类中,用户输入 string,并在输入的 string 上调用 RemoveVowel 扩展 方法,以从 string 中删除元音。

注意

  1. 在这里,扩展方法和客户端都在同一个命名空间中,因此不需要包含扩展方法的命名空间。
  2. 扩展方法的调用方式与其他成员方法一样。
    resultString = str.RemoveVowel();

Program.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ExtensionMethodSample 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            String resultString; 

            Console.WriteLine("Enter Input String to Remove all Vowel using " +
                              "Extension Method \n"); 
            String str = Console.ReadLine(); 
            Console.WriteLine("After Removing Vowel Input String is \n"); 
            resultString = str.RemoveVowel(); 
            Console.WriteLine(resultString); 
            Console.ReadKey(); 
        } 
    } 
}

历史

  • 2009 年 6 月 12 日:初始发布
© . All rights reserved.