C#学习笔记4——扩展方法

有许多方法扩展类。如果有类的源代码,继承就是给对象添加给你的好方法。但如果没有源代码,该怎么办?此时可以使用扩展方法,扩展方法是静态方法,是类的一部分,但实际上没有放在类的源代码中。

定义和调用扩展方法步骤:

1、定义一个静态类以包含扩展方法。该类必须对客户端代码可见。有关可访问性规则的更多信息,请参见访问修饰符。

2、将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。

3、该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。

4、在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。

5、按照与调用类型上的实例方法一样的方式调用扩展方法。

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

下面的示例在 MyExtensions.StringExtension 类中实现了一个名为 WordCount 的扩展方法。该方法对 String类进行操作,而该类被指定为第一个方法参数。MyExtensions 命名空间被导入到应用程序命名空间中,并且该方法是在 Main 方法内调用的。

 

using System.Linq;

using System.Text;

using System;

 

namespace CustomExtensions

{

    //Extension methods must be defined in astatic class

    public static class StringExtension

    {

       // This is theextension method.

       // The firstparameter takes the "this" modifier

       // and specifies thetype for which the method is defined.

       public static int WordCount(thisString 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 thefirst

           //  parameter is not specified by the callingcode.

           int i = s.WordCount();

           System.Console.WriteLine("Wordcount of s is {0}", i);

       }

    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

byxdaz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值