一些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
沒有留言:
張貼留言