Article Directory
foreword
I recently checked how to use the callback function of C#, but after tossing for a long time, I still can't solve it. I see that everything written on the Internet is complicated. But everyone knows that C# is actually a mixture of Java and JS. He inherits the advantages of them and has strong syntactic sugar. Here I am still tossing out how the callback function is written in imitation of JS.
simple async function
definition
I define the callback function here. I just use the callback function as a callback, not as a parameter. The biggest feature of the callback function is asynchrony. That is, I have agreed with you what value you will send back to me, and I will set up the solution. Just wait until you return.
The callback function is as follows (my personal definition)
public void Function(Action<回调参数> callback)
{
...其他步骤
callback(参数);
}
the code
internal class Program
{
private static Person person;
static void Main(string[] args)
{
person = new Person()
{
Name = "小明",
Age = 15
};
person.GetInfo((a,b) =>
{
Console.WriteLine("我是回调函数");
Console.WriteLine($"姓名:{a},年龄{b}");
});
person.GetInfoDelay((a, b) =>
{
Console.WriteLine("我等线程跑完");
Console.WriteLine($"姓名:{a},年龄{b}");
});
Console.ReadLine();
}
}
public class Person{
public string Name {
get; set; }
public int Age {
get; set; }
/// <summary>
/// 回调函数
/// </summary>
/// <param name="callback"></param>
public void GetInfo(Action<string, int> callback)
{
callback(Name, Age);
}
public void GetInfoDelay(Action<string, int> callback)
{
for(var i = 0; i < 10; i++)
{
Console.WriteLine(i);
Thread.Sleep(1000);
}
callback(Name, Age);
}
}