2022年10月17日 星期一

[C#]語法混合應用

一些C# 的基礎應用範例

 int iData = 123;
string str = $"Hello{iData}!!";

Action<string> greet = name =>
{
    string greeting = $"hello {name}!";
    Console.WriteLine(greeting);
};
greet("world");



其他執行續範例說明:
正常寫法如以下兩段:
private void setText(Object str) { using (StreamWriter sw = new StreamWriter(@"D:\test.txt",true,Encoding.UTF8)) { sw.WriteLine(str.ToString()); } } protected void Button1_Click(object sender, EventArgs e) { string str = "測試四"; ThreadPool.QueueUserWorkItem(new WaitCallback(setText),(Object) str); }

透握委派方式簡化程式碼:
protected void Button1_Click(object sender, EventArgs e) { string str = "測試三"; ThreadPool.QueueUserWorkItem(delegate { using (StreamWriter sw = new StreamWriter(@"D:\test.txt", true, Encoding.UTF8)); //路徑 , 不複寫檔案 , 編碼 { sw.WriteLine(str); } }); }

透過Lambda寫法:
protected void Button1_Click(object sender, EventArgs e) { string str = "測試五"; ThreadPool.QueueUserWorkItem(callback => { using (StreamWriter sw = new StreamWriter(@"D:\test.txt", true, Encoding.UTF8)) { sw.WriteLine(str.ToString()); } }); }




參考來源:
https://learn.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/lambda-expressions
https://dotblogs.com.tw/ken74114/2010/12/08/19988

沒有留言:

張貼留言

[SQL]顯示千分位與小數顯示

  CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) CONVERT style參數說明 1  (expression為 money 或 smallmoney型別): 0 : 預設,保留小數位後兩位,並四捨...