码迷,mamicode.com
首页 > 其他好文 > 详细

扩展方法(为那些已经写好不能修改源码的类添加方法)

时间:2017-08-11 23:02:44      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:ati   min   text   实现   访问修饰符   new   first   ide   应用程序   

参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method

本主题介绍如何实现 .NET Framework 类库 中任意类型的扩展方法,或是你想要扩展的任何其他 .NET 类型。 客户端代码可以通过以下方法使用扩展方法,添加包含这些扩展方法的 DLL 的引用,以及添加 using 指令,该指令指定在其中定义扩展方法的命名空间。

定义和调用扩展方法

  1. 定义包含扩展方法的静态

    此类必须对客户端代码可见。 有关可访问性规则的详细信息,请参阅访问修饰符

  2. 扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。

  3. 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符

  4. 在调用代码中,添加 using 指令,用于指定包含扩展方法类的命名空间

  5. 和调用类型的实例方法那样调用这些方法

    请注意,第一个参数并不是由调用代码指定,因为它表示要在其上应用运算符的类型,并且编译器已经知道对象的类型。 你只需通过 n 提供形参 2 的实参

示例

以下示例实现 CustomExtensions.StringExtension 类中名为 WordCount 的扩展方法。 此方法对String 类进行操作,该类指定为第一个方法参数。 将 CustomExtensions 命名空间导入应用程序命名空间,并在 Main 方法内部调用此方法。

C#
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);
        }
    }
}

编译代码

若要运行此代码,请将其复制并粘贴到已在 Visual Studio 中创建的 Visual C# 控制台应用程序项目。 默认情况下,此项目面向 .NET Framework 3.5 版,并且具有对 System.Core.dll 的引用和一个用于 System.Linq 的 using 指令。 如果项目中缺少其中一个或多个要求,则可以手动添加它们。

.NET Framework 安全性

扩展方法不存在特定的安全漏洞。 始终不会将扩展方法用于模拟类型的现有方法,因为为了支持类型本身定义的实例或静态方法,已解决所有名称冲突。 扩展方法无法访问扩展类中的任何隐私数据。

扩展方法(为那些已经写好不能修改源码的类添加方法)

标签:ati   min   text   实现   访问修饰符   new   first   ide   应用程序   

原文地址:http://www.cnblogs.com/dsh20134584/p/7348195.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!