windows C#-如何实现和调用自定义扩展方法

本文将介绍如何为任意 .NET 类型实现自定义扩展方法。 客户端代码可以使用扩展方法。 客户端项目必须引用包含它们的程序集。 客户端项目必须添加一个 using 指令,该指令指定在其中定义扩展方法的命名空间。

定义和调用扩展方法:

  • 定义包含扩展方法的静态类。 该类不能嵌套在另一个类型内,并且必须对客户端代码可见。
  • 将扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。
  • 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符。
  • 在调用代码中,添加 using 指令,用于指定包含扩展方法类的命名空间。
  • 将方法作为类型的实例方法调用。

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

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

复制代码
using CustomExtensions;

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);


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;
        }
    }
}

重载解析首选类型本身定义的实例或静态方法,而不是扩展方法。 扩展方法无法访问扩展类中的任何隐私数据。

相关推荐
Whisper_Sy2 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 网络状态实现
android·java·开发语言·javascript·网络·flutter·php
Bony-3 小时前
Go语言垃圾回收机制详解与图解
开发语言·后端·golang
hmywillstronger3 小时前
【Rhino】【Python】 查询指定字段并cloud标注
开发语言·python
新缸中之脑3 小时前
Weave.js:开源实时白板库
开发语言·javascript·开源
我能坚持多久3 小时前
D16—C语言内功之数据在内存中的存储
c语言·开发语言
leo__5203 小时前
C#与三菱PLC串口通信源码实现(基于MC协议)
开发语言·c#
二十雨辰4 小时前
[python]-函数
开发语言·python
码农水水4 小时前
中国邮政Java面试被问:容器镜像的多阶段构建和优化
java·linux·开发语言·数据库·mysql·面试·php
福楠4 小时前
C++ STL | map、multimap
c语言·开发语言·数据结构·c++·算法
ytttr8734 小时前
地震数据频率波数域变换与去噪的MATLAB实现
开发语言·matlab