c#每日小结 七
擴展方法:必須是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);
??????? }
?
轉載于:https://blog.51cto.com/3298646/617854
總結
- 上一篇: CentOS-6.0下安装配置Cacti
- 下一篇: c# char unsigned_dll