using System;
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price) { Price = price; }
public Wine (decimal price, int year) : this (price) { Year = year; }
}
和以下這段code是等價的
using System;
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price) { Price = price; }
public Wine (decimal price, int year) { Wine(price); Year = year; }
}
一樣都會改Price的值
上網找了一下 發現原來還有很多方便的語法糖 以下節錄幾個常用的
經過兩次變異的委託寫法
真的易用多了一開始推出的時候真的完全看不懂
class MyClass
{
public delegate void DoSomething(int a);
//定義方法委託
private void DoIt(int a) {
Console.WriteLine(a);
}
private void HowtoDo(DoSomething doMethod,int a) {
doMethod(a);
}
public static void Main(string[] args) {
MyClass mc = new MyClass();
//調用定義的方法委託
mc.HowtoDo(new DoSomething(mc.DoIt), 10);
int x = 10;
//使用匿名委託
mc.HowtoDo(delegate(int a){
Console.WriteLine(a + x);
},10);
//使用lamda表達式
mc.HowtoDo(a=>Console.WriteLine(a+x),10);
Console.ReadLine();
}
}
集合類的聲明
以前:
List現在:list = new List (); list.Add("a一"); list.Add("b二"); list.Add("c三");
List集合類各個項的操作list = new List { "def","OK" };
以前:
foreach (string item in list)
{
Console.WriteLine(item);
}
現在(朝FP之路邁進?XD):
list.ForEach(a => Console.WriteLine(a));傳說中的擴展方法
擴展一個String的方法:
public static class StringExt {
static private Regex regexNumber = new Regex("\\d+");
static public bool IsNumber(this string input)
{
if (string.IsNullOrEmpty(input))
{
return false;
}
return regexNumber.IsMatch(input);
}
}
使用:
var abc = "123"; var isNumber = abs.IsNumber();有興趣知更多的可以到原站看看 再post多次連結: C#語法糖(Csharp Syntactic sugar)大匯總
其實語法糖很常見 只是不知道為什麼C#好像特別多(還是說玩C#的都很懶?)
沒有留言:
張貼留言