c#每日小结 七
擴(kuò)展方法:必須是static,但是調(diào)用的時(shí)候像調(diào)用普通方法一樣調(diào)用;
例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExterString;//加入引用空間
?
namespace 擴(kuò)展方法
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? string s = "abbba";
?
??????????? foreach (int i in s.IndexOfAll("a"))
??????????? {
???????? ???????Console.Write(i+"??? ");
??????????? }
?
?
??????? }
??? }
}
//定義擴(kuò)展方法
namespace ExterString
{
??? static class Exterlp
??? {
??????? public static int[] IndexOfAll(this string str, string s)//注意前面的static,括號中的參數(shù) ,
??????? {
??????????? 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;
?
??????? }
??? }
}
匿名方法:沒有方法簽名,與委托配合使用;由于不必創(chuàng)建單獨(dú)的方法,減少了實(shí)例化委托所需的代碼系統(tǒng)開銷;
例:this.load +=delegate{string s=”?? ”};
命名參數(shù):可以按形參名稱賦值;
注意:如果使用匿名參數(shù),必需所有的參數(shù)都命名;
例:
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);
??????? }
?
?
可選 參數(shù):
注意:在形參列表的末尾定義,必須放在必需形參(普通參數(shù) ,區(qū)別于可選參數(shù))之后;方法,構(gòu)造函數(shù),索引器,委托的定義可以指明其形參是必需的還是可選 的;任何調(diào)用都必須為必需的形參提供實(shí)參,可以省略可選形參的實(shí)參;
例:
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);
??????? }
?
轉(zhuǎn)載于:https://blog.51cto.com/3298646/617854
總結(jié)
- 上一篇: CentOS-6.0下安装配置Cacti
- 下一篇: C#温故而知新学习系列之XML编程—Xm