Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试调用方法时无法从void转换为System.Action_C# - Fatal编程技术网

C# 尝试调用方法时无法从void转换为System.Action

C# 尝试调用方法时无法从void转换为System.Action,c#,C#,我有以下代码: public void UpdateDConfDictionaryToCol(DconF dconF) { var allDconf = GetDConfFromCol(); allDconf[dconF.id.ToString()] = dconF; var serializeJson = Helpers.JsonConverter.SerializeEscapeHtml(

我有以下代码:

    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);
    }
我想计算执行所需的时间,因此我尝试使用我的应用程序具有的一些代码:

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;
    }
}
下面是我使用它的地方:

var abc = Helper.Timer(App.CM.UpdateDConfDictionaryToCol(App.CM.SelectedDconf));
但它给了我一条错误信息,说:

argument 1, cannot convert from void to system Action
您正在将App.CM.UpdateDConfDictionaryToColApp.CM.SelectedConf传递给Helper.Timer。它返回void并被计算为Helper.Timer方法的参数。但是,Helper.Timer需要一个操作。这就是您看到的错误的原因

您可以执行以下操作

// 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);
仅供参考,StartNew创建一个新秒表,然后启动它。你不必事后打电话给Start。但是,您通常会在返回经过的时间之前调用Stop。因为UpdateDConfDictionaryToCol返回void,这意味着您的代码变为:var abc=Helper.Timervoid;,但是计时器方法需要一个操作,因此您会得到该错误。
var abc = Helper.Timer(() => App.CM.UpdateDConfDictionaryToCol(App.CM.SelectedDconf))