【转】C# 委托(Func、Action)
2021-03-10 22:32
标签:ret fir first 类型 方便 根据 lse 一个 return 原文地址: 1、Func 用法 (封装方法,传入参数, 有返回值) Func 封装一个方法,该方法有 (0 /1/2/3 ... 16)个参数,且返回由 TResult 参数指定的值的类型。 2、Action 用法 (封装一个方法, 传入参数, 无返回值) Action 封装一个方法, 该方法传入 (0/1/2 ...) 个参数, 且不返回值。 3. 委托的使用 讲了两种不同情况的委托, 那么什么时候使用委托呢? 根据官方文档,在以下情况下,请使用委托: 4. 在 Task 使用委托 Task 表示一个异步操作。 运行结果如下 : main thread has end:2018-03-04 22:03:39 First task finished time is:2018-03-04 22:03:40 second task finished time is:2018-03-04 22:03:41 third task finished time is:2018-03-04 22:03:42 the third task has finished 【转】C# 委托(Func、Action) 标签:ret fir first 类型 方便 根据 lse 一个 return 原文地址:https://www.cnblogs.com/louiszh/p/12665828.html
https://cloud.tencent.com/developer/article/1335104public static void Main()
{
// 方法一: Func 相当于系统内置的 委托
Funcint, int, string> method = Calculate;
// 方法二: 调用 Lambda 方法实现, 更简洁
Funcint, int, string> method_1 = (x, y) =>
{
int val = x + y;
return string.Format("the calculate {0} plus {1} result is: {2}", x, y, val);
};
Console.WriteLine(method(3, 5));
Console.WriteLine(method_1(10, 18));
Console.ReadLine();
}
public static string Calculate(int x, int y)
{
int val = x + y;
return string.Format("the calculate {0} plus {1} result is: {2}", x, y, val);
}
public static void Main()
{
Method_First("Hi, Here!");
Method_First("Hi, There!");
Console.ReadLine();
}
private static void Method_First(string y)
{
Actionstring> method;
method = x => { Console.WriteLine("the input message is: {0}", x); };
method(y);
}
private static void Method_Sec(string y)
{
Actionstring> method = x => { Console.WriteLine("the input message is : {0}", x); };
method(y);
}
public static void Main()
{
// 启动方法1
Task t = Task.Run(() =>
{
Thread.Sleep(1000);
Console.WriteLine("First task finished time is:{0}", DateTime.Now.ToString());
});
// 方法2
Task t_2 = Task.Factory.StartNew(() => {
Thread.Sleep(2000);
Console.WriteLine("second task finished time is:{0}", DateTime.Now.ToString());
});
// 方法 3
Action action = () =>
{
Thread.Sleep(3000);
Console.WriteLine("third task finished time is:{0}", DateTime.Now.ToString());
};
Task.Factory.StartNew(action).ContinueWith(thirdTask =>
{
if (thirdTask.IsCompleted)
{
Console.WriteLine("the third task has finished");
}
else if (thirdTask.IsFaulted)
{
Console.WriteLine(thirdTask.Exception);
}
});
Console.WriteLine("main thread has end:{0}",DateTime.Now.ToString() );
Console.ReadKey();
}