扩展方法。
引用msdn上的一句话:
“扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。”
我们可以在没有源代码,不改变源代码的基础上,给基础类型比如int上添加一些方法。
使用扩展方法的要求:
第一,实现扩展方法的类必须是静态类且类的名称和实现扩展方法的类无关;后一句大概是你要扩展int类,你静态类名不能叫int吧。
第二、实现扩展方法的类方法必须是静态方法;
第三、实现扩展方法的类方法的第一个参数必须是使用this关键字指明要实现扩展方法的类。
而C#支持扩展方法是从.NET3.5版本开始。
下面的代码扩展了int类,增加了求一个数的平方和一个数加另一个数的和的平方的方法,分别是传参数和不传参数的扩展方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myspace;
namespace extended_method
{
class Program
{
static void Main(string[] args)
{
int k = 5, j = 3;
Console.WriteLine("k's square: " + k.getSquare());
Console.WriteLine("k plus j then square: " + k.plusToSquare(j));
}
}
}
namespace myspace
{
/// <summary>
/// 1、定义一个静态类
/// 2、静态类的名称和要实现扩展方法的具体类无关
/// </summary>
/// <summary>
/// 3、实现一个具体的静态方法
/// </summary>
/// <param name="n">4、第一个参数必须使用this关键字指定要使用扩展方法的类型</param>
/// <returns></returns>
public static class squareNum
{
public static int getSquare(this int n)
{
return n * n;
}
}
public static class plusANumbertoSquare
{
public static int plusToSquare(this int n,int k)
{
return (n + k) * (n + k);
}
}
}
yield,IEnumerable和IEnumerator
参考:http://www.cnblogs.com/vivid-stanley/p/5272736.html
C#语法中有个特别的关键字yield。
yield 是在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yield return ;
yield break
IEnumerable的定义
namespace System.Collections
{
//
// 摘要:
// 公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
[ComVisible(true)]
[Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
public interface IEnumerable
{
//
// 摘要:
// 返回一个循环访问集合的枚举器。
//
// 返回结果:
// 可用于循环访问集合的 System.Collections.IEnumerator 对象。
[DispId(-4)]
IEnumerator GetEnumerator();
}
}
转到IEnumerator的定义,我们看到IEnumerator接口定义了一个Current属性,MoveNext和Reset两个方法。
using System.Runtime.InteropServices;
namespace System.Collections
{
//
// 摘要:
// 支持对非泛型集合的简单迭代。
[ComVisible(true)]
[Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
public interface IEnumerator
{
//
// 摘要:
// 获取集合中的当前元素。
//
// 返回结果:
// 集合中的当前元素。
object Current { get; }
//
// 摘要:
// 将枚举数推进到集合的下一个元素。
//
// 返回结果:
// 如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
//
// 异常:
// T:System.InvalidOperationException:
// 在创建了枚举数后集