[英]Cannot convert from void to System.Action when trying to call a method
I have this code:我有这个代码:
public void UpdateDConfDictionaryToCol(DconF dconF)
{
var allDconf = GetDConfFromCol();
allDconf[dconF.id.ToString()] = dconF;
var serializeJson = Helpers.JsonConverter.SerializeEscapeHtml(allDconf);
App.CM.UpdateCol(serializeJson,CONST.dconfCol);
}
I would like to time how long it takes to execute so I am trying to use some code that my application has:我想计算执行需要多长时间,所以我尝试使用我的应用程序具有的一些代码:
public static partial class Helper
{
public static string Timer(Action action)
{
var stopWatch = Stopwatch.StartNew();
stopWatch.Start();
action();
return stopWatch.ElapsedMilliseconds.ToString();
}
public static int TimerInt(Action action)
{
var stopWatch = Stopwatch.StartNew();
stopWatch.Start();
action();
return (int) stopWatch.ElapsedMilliseconds;
}
}
Here is where I am using it:这是我使用它的地方:
var abc = Helper.Timer(App.CM.UpdateDConfDictionaryToCol(App.CM.SelectedDconf));
But it gives me an error message saying:但它给了我一条错误消息:
argument 1, cannot convert from void to system Action
You are passing in App.CM.UpdateDConfDictionaryToCol(App.CM.SelectedDconf)
to the Helper.Timer
.您正在将
App.CM.UpdateDConfDictionaryToCol(App.CM.SelectedDconf)
传递给Helper.Timer
。 That returns void and gets evaluated to be a parameter to Helper.Timer
method.这将返回 void 并被评估为
Helper.Timer
方法的参数。 However, Helper.Timer
expects an action.但是,
Helper.Timer
需要一个动作。 This is the reason for the error you are seeing.这就是您看到的错误的原因。
You may do the following您可以执行以下操作
// Pass the action as a parameter and invoke this inside the method with the parameter
// The action in this case should be Action<T> where T is DConf
var abc = Helper.Timer(App.CM.UpdateDConfDictionaryToCol);
// invoking the action with the parameter within Helper.Timer
// However, the helper needs to know of the parameter App.CM.UpdateConf separately. Another
// simpler alternative is provided in the second approach below
action(App.CM.UpdateConf);
OR或者
Always, in general, make sure to pass the delegate ( Action
in this case) as shown below and do not pass call to the method directly as that gets evaluated to the return type of the method but not as a delegate as we expect it to be.通常,始终确保传递委托(在这种情况下为
Action
),如下所示,并且不要直接将调用传递给方法,因为它会被评估为方法的返回类型,而不是像我们期望的那样作为委托是。
var abc = Helper.Timer(() => App.CM.UpdateDConfDictionaryToCol(App.CM.SelectedDconf))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.