扩展方法:必须是static,但是调用的时候像调用普通方法一样调用;
例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExterString;//加入引用空间
namespace 扩展方法
{
class Program
{
static void Main(string[] args)
{
string s = "abbba";
foreach (int i in s.IndexOfAll("a"))
{
Console.Write(i+" ");
}
}
}
}
//定义扩展方法
namespace ExterString
{
static class Exterlp
{
public static int[] IndexOfAll(this string str, string s)//注意前面的static,括号中的参数 ,
{
char[] ch = new char[str.Length];
int[] aindex = new int[str.Length];
int count = 0;
for (int i = 0; i < str.Length; i++)
{
aindex[i] = -1;
}
str.CopyTo(0, ch, 0, str.Length);
for (int i = 0; i < str.Length; i++)
{
if (ch[i].ToString() == s)
{
for (int j = 0; j < str.Length; j++)
{
if (aindex[j] == -1)
{
aindex[j] = i;
count++;
break;
}
}
}
}
int[] index = new int[count];
for (int j = 0; j < str.Length; j++)
{
if (aindex[j] != -1)
{
for (int i = 0; i < count; i++)
{
index[i] = aindex[j];
break;
}
}
}
return index;
}
}
}
匿名方法:没有方法签名,与委托配合使用;由于不必创建单独的方法,减少了实例化委托所需的代码系统开销;
例:this.load +=delegate{string s=” ”};
命名参数:可以按形参名称赋值;
注意:如果使用匿名参数,必需所有的参数都命名;
例:
static void Main(string[] args)
{
ss(name: "gxr", weight: 45.0, age: 20);
}
static void ss(string name,int age,double weight)
{
Console.WriteLine(name+age+weight);
}
可选 参数:
注意:在形参列表的末尾定义,必须放在必需形参(普通参数 ,区别于可选参数)之后;方法,构造函数,索引器,委托的定义可以指明其形参是必需的还是可选 的;任何调用都必须为必需的形参提供实参,可以省略可选形参的实参;
例:
static void Main(string[] args)
{
ss("gxrrrr");
}
static void ss(string name, int age = 20, double weight = 456)
{
Console.WriteLine("{0},{1},{2}", name, age, weight);
}