C#語言語法講座-更新到C#3.0特性
C#3.0特性
l匿名類型砖顷,類螟够,方法
如果只用一次,盡量使用匿名恳守,避免沖突
var obj = new { name = ”zhangxx” , age = 30};
Console.WriteLine(obj.name);
l自動屬性和類的快速初始化
public class EmployeeItem{
public string EmpID{get;set;}
public string EmpName{get;set;}
}
EmployeeItem ei = new EmployeeItem{EmpID=”002”,EmpName=”Hu”}; // C#3.0
l拓展方法
public static class Suibian{
public static String Talk(this String h){
return “hello string”;
}
}
調(diào)用方法
string testString = “”.Talk();
//結果為hello string
注:當拓展方法與原類方法同名時默認使用原類的方法榄审。
l數(shù)據(jù)結構和算法
引入Linq來處理內(nèi)存的數(shù)據(jù)
Linq2Object像SQL一樣處理結合類數(shù)據(jù)(包含枚舉類型的數(shù)據(jù))
老的做法是:用SQL讀取出來砌们,要匯總也要先匯總。微軟想用SQL那樣成熟的方法來操作數(shù)據(jù)搁进,用的是C#的語法浪感。
Int[] arr1 = {12 , 3 , 6 , 4 , 90 , 96 , 56};
string testString = from a in arr1
where panduan(a)
order by descending
select a;
private bool panduan(int a){
//此處做判斷
return a%3 == 0;
}
Linq拓展// Lambda表達式
string testString = arr1.Where(x=> x>10);
//結果為12,90,96,56
string testString = arr1.Where(x=> x>10).OrderByDescending(y=> y);
//結果為96,90, 56,12
//點號后面還有很多方法,可以去學習饼问。
Int[] arr1 = {12 , 3 , 6 , 4 , 90 , 96 , 56};
Int[] arr2 = {-1 , -2 , 12 , 3 , 6 };
string testString = arr1.Except(arr2);
//結果為4,90,96,56