Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

using ExtensionMethods;
string s = "Hello Extension Methods";
int i = s.WordCount();

This topic shows how to implement your own extension methods for any type in the .NET Framework Class Library, or any other .NET type that you want to extend. Client code can use your extension methods by adding a reference to the DLL that contains them, and adding a usingdirective that specifies the namespace in which the extension methods are defined.

To defining and call the extension method

  1. Define a static class to contain the extension method.

    The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).

  2. Implement the extension method as a static method with at least the same visibility as the containing class.

  3. The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.

  4. In the calling code, add a using directive to specify the namespace that contains the extension method class.

  5. Call the methods as if they were instance methods on the type.

    Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值