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 ...
随机推荐
- redis集群——RPLR简笔(Redis+PostgreSQL+Linux(centos7)+RabbitMQ)
使用的是centos7. 1.下载最新redis源码,解压(2016-05-12最新版本为3.2.0,3.0及以上才有官方集群) 2.进入源码根目录(此目录下的redis-stable目录),找到ut ...
- GNSS数据下载网站
Bernese 数据表文件下载 rinex文件下载 ftp://nfs.kasi.re.kr DCB.ION文件ftp://ftp.unibe.ch/AIUB/CODE/ 下载5.0更新文件 ftp: ...
- 洛谷——P1966 火柴排队&&P1774 最接近神的人_NOI导刊2010提高(02)
P1966 火柴排队 这题贪心显然,即将两序列中第k大的数的位置保持一致,证明略: 树状数组求逆序对啦 浅谈树状数组求逆序对及离散化的几种方式及应用 方法:从前向后每次将数插入到bit(树状数组)中, ...
- Cashier (codeforces 1059A)
题目倒是不难注意第一个时间段可能不是从零开始的,所以注意第一个时间的开始节点与零之间可能存在休息的时间 还有这个题我打的时候一直谜之RE......发现原来bool函数忘记写return了.....以 ...
- python 易忘操作整理
>>> l=[1,2,3,4,5] >>> s='$'.join(str(i) for i in l) >>> print(s,end=" ...
- ansible - 基本用法
目录 ansible - 01 一. 安装与使用 ansible命令格式 查看ansible生成的配置文件 ssh认证方式 ansible的第一个命令 弱口令校验 host-pattern的格式 模块 ...
- PAT 1096. Consecutive Factors
Among all the factors of a positive integer N, there may exist several consecutive numbers. For exam ...
- 3D全景之ThreeJs
3D全景之ThreeJs 一.前言 随着H5越来越多的被应用到各个领域,3D也越来越频繁的出现在各个H5案例中,今天我们就来讨论一下3D全景的实现. 据百度百科上介绍:720全景是视角超过人的正常视角 ...
- 多层gmetad配置
经实验表明: ①多层gmetad与ganglia版本无关,且可以多版本兼容 ②多层gmetad只有最底层gmetad能保存详细指标,非底层gmetad收集到的都只能是summary信息,当然也许我配置 ...
- Django——9 博客小案例的实现
Django 博客小案例的实现 主要实现博客的增删改查功能 主页index.html --> 展示添加博客和博客列表的文字,实现页面跳转 添加页add.html --> 输入文章标 ...