Extension Methods (C# Programming Guide)
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)的更多相关文章
- Interfaces (C# Programming Guide)
https://msdn.microsoft.com/en-us/library/ms173156.aspx An interface contains definitions for a group ...
- 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 ...
- Polymorphism (C# Programming Guide)
https://msdn.microsoft.com/en-us/library/ms173152.aspx Polymorphism is often referred to as the thir ...
- [IoLanguage]Io Programming Guide[转]
Io Programming Guide Introduction Perspective Getting Started Downloading Installing Binaries Ru ...
- Extension Methods "点"函数方法 扩展方法
原文发布时间为:2011-03-25 -- 来源于本人的百度文章 [由搬家工具导入] http://msdn.microsoft.com/en-us/library/bb383977.aspx 条件: ...
- 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 ...
- 【IOS笔记】View Programming Guide for iOS -1
原文:View Programming Guide for iOS View and Window Architecture Views and windows present your applic ...
- View Programming Guide for iOS_读书笔记[正在更新……]
原文:View Programming Guide for iOS 1 Introduction 先熟悉一下基本概念. Window Windows do not have any visible c ...
- 对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 ...
随机推荐
- Android项目实战_手机安全卫士流量统计
## 1.抽屉控件SlidingDrawer:一定要配置android:handle(把手)和android:content(内容),并在子View中添加把手和内容的布局```java <Sli ...
- Android studio USB连接失败
Android studio USB连接失败,可能是因为adb的端口被占了,此时在其自带的cmd中输入netstat -aon|findstr "5037",并且启动任务管理器关掉 ...
- sql server 大数据跨服务器迁移表数据——使用链接服务器
1.创建链接服务器(填写链接服务器.远程登录.使用密码) 2.188.188.1.177是远程的 select count(*) from [188.188.1.177].BigDataAnalysi ...
- Coding iOS客户端应用源码
Coding是国内的一家提供Git托管服务的产品,它们的客户端提供了项目和任务管理.消息和用户中心,以及一个类似论坛的功能,已经在App Store上线: https://itunes.apple.c ...
- JAVA如何获得数据库的字段及字段类型
Java获取数据库的表中各字段的字段名,代码如下: import java.sql.Connection;import java.sql.DriverManager;import java.sql.R ...
- Node.js之错误处理
Node.js之错误处理 1. 使用 domain 模块处理错误 try..catch 多用于捕捉同步方法中的抛出错误,但不能用try..catch捕捉异步方法中抛出de错误 如: 1 var htt ...
- c/c++排坑(3) -- c/c++中的switch语句
switch语句的简单介绍 一个 switch 语句允许测试一个变量等于多个值时的情况.每个值称为一个 case,且被测试的变量会对每个 switch case 进行检查. switch(expres ...
- 洛谷——P1572 计算分数
P1572 计算分数 模拟+字符串 注意有两位数的情况以及负数情况 #include<bits/stdc++.h> using namespace std; string s; ],b[] ...
- HDU-5968异或密码
超级传送门 题目描述: 晨晨在纸上写了一个长度为N的非负整数序列{ai}.对于这个序列的一个连续子序列{al,al+1,…,ar}晨晨可以求出其中所有数异或的结果 alxoral+1xor...xor ...
- 31.IK分词器配置文件讲解以及自定义词库
主要知识点: 知道IK默认的配置文件信息 自定义词库 一.ik配置文件 ik配置文件地址:es/plugins/ik/config目录 IKAnalyzer.cfg.xml:用 ...