A function that takes a delegate as a parameter must use a named delegate type; unlike in Objective-C you can't declare an anonymous delegate type inline in the function definition. However, the generics Action<> and Func<> are provided so that you don't have to declare a new type yourself. In the code below I'm assuming the delegate takes a single int
as a parameter.
void DoSomethingWithCallback(Func<int,Task> callbackDelegate)
{
Task t = callbackDelegate(42);
}
If this function doesn't actually do anything with the Task object returned (as with the code shown above), you can instead use Action<int>
as the delegate type. If you use Action, you can still declare the delegate async (below) but the implicit Task object returned is ignored.
The lambda syntax for calling the above function is straightforward and the syntax you used in the question is correct. Note that the parameter type doesn't need to be specified here since it can be inferred:
DoSomethingWithCallback(async (intParam) => { this.myint = await Int2IntAsync(intParam); });
You can also pass a method or delegate variable, if you wish, instead of using the lambda syntax:
async Task MyInt2Int(int p) { ... }
Func<int,Task> myDelegate;
void OtherMethod()
{
myDelegate = MyInt2Int;
DoSomethingWithCallback(myDelegate); // this ...
DoSomethingWithCallback(MyInt2Int); // ... or this.
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…