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

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

相关推荐
bjxiaxueliang15 分钟前
一文掌握C/C++命名规范:风格、规则与实践详解
c语言·开发语言·c++
玄〤31 分钟前
Java 大数据量输入输出优化方案详解:从 Scanner 到手写快读(含漫画解析)
java·开发语言·笔记·算法
一起养小猫38 分钟前
Flutter for OpenHarmony 实战:番茄钟应用完整开发指南
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
独自破碎E39 分钟前
总持续时间可被 60 整除的歌曲
java·开发语言
senijusene44 分钟前
数据结构与算法:队列与树形结构详细总结
开发语言·数据结构·算法
好好沉淀1 小时前
Elasticsearch 中获取返回匹配记录总数
开发语言·elasticsearch
2301_765703141 小时前
C++与自动驾驶系统
开发语言·c++·算法
MediaTea1 小时前
<span class=“js_title_inner“>Python:实例对象</span>
开发语言·前端·javascript·python·ecmascript
热爱编程的小刘1 小时前
Lesson04---类与对象(下篇)
开发语言·c++·算法
毕设源码-朱学姐2 小时前
【开题答辩全过程】以 基于Java的九价疫苗预约系统为例,包含答辩的问题和答案
java·开发语言