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

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

相关推荐
mudtools15 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下21 小时前
最终的信号类
开发语言·c++·算法
echoarts21 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix21 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz21 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号1 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_1 天前
QT(4)
开发语言·汇编·c++·qt·算法