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

private static void Dump(this ArraySegment<byte> segment)
{
string output = string.Join(",", segment.Select(x => x.ToString()));
Console.WriteLine(output);
}

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.

The most common extension methods are the LINQ standard query operators that add query functionality to the existingSystem.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types.

To use the standard query operators, first bring them into scope范围 with a using System.Linq directive.

Then any type that implements IEnumerable<T> appears to have instance methods such asGroupBy<TSource, TKey>OrderBy<TSource, TKey>Average, and so on.

You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable<T> type such as List<T> or Array.

The following example shows how to call the standard query operator OrderBy method on an array of integers.

The expression in parentheses圆括号 is a lambda expression.

Many standard query operators take lambda expressions as parameters, but this is not a requirement for extension methods.

For more information, see Lambda Expressions (C# Programming Guide).

class ExtensionMethods2
{ static void Main()
{
int[] ints = { , , , , , };
var result = ints.OrderBy(g => g);
foreach (var i in result)
{
System.Console.Write(i + " ");
}
}
}

Extension methods are defined as static methods but are called by using instance method syntax.

Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

The following example shows an extension method defined for the System.String class.

Note that it is defined inside a non-nested, non-generic static class:

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

The WordCount extension method can be brought into scope with this using directive:

using ExtensionMethods;

And it can be called from an application by using this syntax:

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

In your code you invoke the extension method with instance method syntax.

However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method.

Therefore, the principle of encapsulation is not really being violated违反.

In fact, extension methods cannot access private variables in the type they are extending.

For more information, see How to: Implement and Call a Custom Extension Method (C# Programming Guide).

In general, you will probably be calling extension methods far more often than implementing your own.

Because extension methods are called by using instance method syntax, no special knowledge is required to use them from client code.

To enable extension methods for a particular type, just add a using directive for the namespace in which the methods are defined.

For example, to use the standard query operators, add this using directive to your code:

using System.Linq;

(You may also have to add a reference to System.Core.dll.)

You will notice that the standard query operators now appear in IntelliSense as additional methods available for most IEnumerable<T> types.

Note:

Although standard query operators do not appear in IntelliSense for String, they are still available.

Extension Methods (C# Programming Guide)的更多相关文章

  1. Interfaces (C# Programming Guide)

    https://msdn.microsoft.com/en-us/library/ms173156.aspx An interface contains definitions for a group ...

  2. Versioning with the Override and New Keywords (C# Programming Guide)

    The C# language is designed so that versioning between base and derived classes in different librari ...

  3. Polymorphism (C# Programming Guide)

    https://msdn.microsoft.com/en-us/library/ms173152.aspx Polymorphism is often referred to as the thir ...

  4. [IoLanguage]Io Programming Guide[转]

    Io Programming Guide     Introduction Perspective Getting Started Downloading Installing Binaries Ru ...

  5. Extension Methods "点"函数方法 扩展方法

    原文发布时间为:2011-03-25 -- 来源于本人的百度文章 [由搬家工具导入] http://msdn.microsoft.com/en-us/library/bb383977.aspx 条件: ...

  6. Table View Programming Guide for iOS---(四)---Navigating a Data Hierarchy with Table Views

    Navigating a Data Hierarchy with Table Views 导航数据表视图层次 A common use of table views—and one to which ...

  7. 【IOS笔记】View Programming Guide for iOS -1

    原文:View Programming Guide for iOS View and Window Architecture Views and windows present your applic ...

  8. View Programming Guide for iOS_读书笔记[正在更新……]

    原文:View Programming Guide for iOS 1 Introduction 先熟悉一下基本概念. Window Windows do not have any visible c ...

  9. 对Spark2.2.0文档的学习3-Spark Programming Guide

    Spark Programming Guide Link:http://spark.apache.org/docs/2.2.0/rdd-programming-guide.html 每个Spark A ...

随机推荐

  1. Java&Xml教程(七)使用JDOM修改XML文件内容

    JDOM提供了非常灵活的方式操作XML文件,使用JDOM非常简单而且代码简洁可读性强.前面我们学习了如何使用JDOM解析XML文件,本节介绍如何使用JDOM修改XML文件内容. 在这个教程中,我们准备 ...

  2. C#——数据库的访问

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. spark的体系结构

    spark的体系结构 1.客户端(Driver Program) 需要构建一个对象,核心是sc(SparkContext) 以应用程序为例:链接本地 //new conf val conf=new S ...

  4. webstrom常用键

    常用快捷键—Webstorm入门指南 提高代码编写效率,离不开快捷键的使用,Webstorm拥有丰富的代码快速编辑功能,你可以自由配置功能快捷键. 快捷键配置 点击“File”-> “setti ...

  5. C# MVC ajax上传 文件

    用普通的ajax提交表单的时候,不能把文件流传到后端去,所以要用到jquery.form.js jquery.form.js到官网下载或者从这里下载:http://pan.baidu.com/s/1c ...

  6. [系统资源攻略]CPU

    linux系统中如何查看cpu信息? 查看linux版本.cpu.位数.内核.内存等信息 linux下查看CPU,内存,机器型号,网卡等信息的方法 查看服务器物理CPU数和CPU核数方法介绍 可以用/ ...

  7. Whl自助搜索下载器

    本文转载自以下链接:https://github.com/Light-City/AutoDownloadWhl 源码地址: https://github.com/Light-City/AutoDown ...

  8. Map的两种遍历方式

    ********************************************************************************* ****************** ...

  9. mongodb数据库的导出与导入

    数据库的导出 导出类型为json,数据库:mapdb,集合:bike 字段:bikeId,lat,lng,current_time,source ,条件为source字段为ofo第一条数据 mongo ...

  10. DFA最小化实例

    原始DFA如下图所示 最小化的定义:1.没有多余的状态(死状态):2.没有两个状态是相互等价的: 两个状态等价的含义:1.兼容性(一致性)——同是终态或同是非终态:2.传播性(蔓延性)——从s出发读入 ...