适应通用动作< T>代表非通用行动代表 [英] Adapt generic action<T> delegates to non-generic action delegate
本文介绍了适应通用动作< T>代表非通用行动代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于如何正确调整通用Action代理到简单的非泛型Action代理版本的问题。
我有一段代码。我希望你能指出我的错误或建议其他一些方法来实施。我对捕获方法论证的背景有疑问
I have a question on how to properly adapt generic Action delegates to simple non-generic version of Action delegate.
I have a piece of code. I wish you could point to my errors or advise some other way to implement. I do have a doubt over capturing context of method arguments
public static class TaskUtils
{
///
/// Executes ACTION delegate
///
///
///
///
public static Task ExecuteAction(Action action, bool isAsync = true)
{
// validate action delegate
Action execAction = Ensure.ArgumentNotNull(action, nameof(action), "Action delegate is not set (NULL)");
if (!isAsync)
{
// do action execute
try
{
execAction();
return Task.CompletedTask;
} catch (Exception ex)
{
// failed handler
return Task.FromException(ex);
}
}
// run a task in the system thread-pool
return Task.Run(action, CancellationToken.None);
}
///
/// Adapter function to fit ACTION delegte
///
///
///
///
///
public static Action AdaptToRootAction(Action action, T arg)
{
// copy param
T param = arg;
return delegate
{
// pass parameter
// and invoke ACTION
action(param);
};
}
public static Action AdaptToRootAction(Action action, T1 arg1, T2 arg2)
{
T1 param1 = arg1;
T2 param2 = arg2;
return delegate
{
// pass two generic parameters
// and invoke ACTION delegate
action(param1, param2);
};
}
public static Action AdaptToRootAction(Action action, T1 arg1, T2 arg2, T3 arg3)
{
T1 param1 = arg1;
T2 param2 = arg2;
T3 param3 = arg3;
return delegate
{
// pass three generic parameters
// and invoke ACTION delegate
action(param1, param2, param3);
};
}
///
/// Executes a generic with a passed value of type
///
///
///
///
///
///
public static Task ExecuteAction(Action action, T arg, bool isAsync = true)
{
// adapt to root Action delegate and invoke
Action rootAction = AdaptToRootAction(action, arg);
return ExecuteAction(rootAction, isAsync);
}
public static Task ExecuteAction(Action action, T1 arg1, T2 arg2, bool isAsync = true)
{
// adapt to root Action delegate and invoke
Action rootAction = AdaptToRootAction(action, arg1, arg2);
return ExecuteAction(rootAction, isAsync);
}
}
我尝试了什么:
我试图使用我的
What I have tried:
I tried to use my
TaskUtils
class
推荐答案
我会为你做一个方法调用...你需要告诉Action会发生什么,就像方法包装器一样:
I'll do one of your method calls for you... you need to tell the Action what to expect, just like the method wrapper:
public static Action AdaptToRootAction<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2)
{
T1 param1 = arg1;
T2 param2 = arg2;
return delegate
{
// pass two generic parameters
// and invoke ACTION delegate
action(param1, param2);
};
}
这篇关于适应通用动作< T>代表非通用行动代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文