柚子快报邀请码778899分享:C#扩展方法
扩展方法:
首先是一种方法,他可以用来扩展已定义类型中的方法成员
扩展方法定义规则:
①扩展方法必须在一个非嵌套、非泛型的静态类中定义
②他至少要有一个参数
③第一个参数必须加上this关键字作为前缀(第一个参数类型也称为扩展类型,即指方法对这个类型的扩展)
④第一个参数不能使用任何其他修饰符(如不能使用ref,out等修饰符)
⑤第一个参数的类型不能是指针类型
扩展方法图示:
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 扩展方法
{
class Program
{
static void Main(string[] args)
{
List
int jsum = source.Jsum();
Console.WriteLine("jsum:" + jsum);
Console.Read();
}
}
public static class ListExten
{
//定义扩展方法
//同public static int Jsum(this List
public static int Jsum(this IEnumerable
{
if (source == null)
{
throw new ArgumentException("输入数组为空");
}
int jsum = 0;
//flag变量用作下标,以计算所有技术下标之和
bool flag = false;
foreach (int current in source)
{
if (!flag)
{
jsum += current;
flag = true;
}
else
{
flag = false;
}
}
return jsum;
}
}
}
运行效果:
柚子快报邀请码778899分享:C#扩展方法
发表评论