zoukankan      html  css  js  c++  java
  • Extension Methods "点"函数方法 扩展方法

    原文发布时间为:2011-03-25 —— 来源于本人的百度文章 [由搬家工具导入]

    http://msdn.microsoft.com/en-us/library/bb383977.aspx

    条件:静态类、静态方法、this 参数、第一个参数为this 参数,从第二个开始传值。。。


    调用:第一个参数类型值.方法(第二个参数值开始传参。。。。)

     

    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.

    ==============================

    using System.Linq;

    using System.Text;
    using System;

    namespace CustomExtensions
    {
    //Extension methods must be defined in a static class
    publicstaticclass StringExtension
    {
    // This is the extension method.
    // The first parameter takes the "this" modifier
    // and specifies the type for which the method is defined.
    publicstaticint WordCount(this String str)
    {
    return str.Split(newchar[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
    }
    }
    }
    namespace Extension_Methods_Simple
    {
    //Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
    staticvoid 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 the first
    // parameter is not specified by the calling code.
    int i = s.WordCount();
    System.Console.WriteLine("Word count of s is {0}", i);
    }
    }
    }

  • 相关阅读:
    hexo部署失败如何解决
    github设置添加SSH
    鼠标相对于屏幕的位置、鼠标相对于窗口的位置和获取鼠标相对于文档的位置
    git push origin master 错误解决办法
    js设计模式:工厂模式、构造函数模式、原型模式、混合模式
    d3.js实现自定义多y轴折线图
    计算机网络之HTTP(上)基础知识点
    Node.js学习笔记(一)基础介绍
    计算机组成
    Ajax及跨域
  • 原文地址:https://www.cnblogs.com/handboy/p/7163937.html
Copyright © 2011-2022 走看看