首页 > 解决方案 > 带有 void 的 C# 8.0 switch 语句

问题描述

我收到以下错误:Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

public void LogClientSideErrors(string message, ValidationType validationType)
        => validationType switch
            {
                ValidationType.Success => setInfo(message, controllerInfo),
                ValidationType.Critical => setFatal(message, controllerInfo),
                ValidationType.Error => setError(message, controllerInfo),
                ValidationType.Exception => setError(message, controllerInfo),
                ValidationType.Information => setInfo(message, controllerInfo),
                ValidationType.Warning => setWarn(message, controllerInfo),
                _ => setError("invalid enum value", controllerInfo),
            }; 

更新:工作解决方案:

internal static void GenerateLogs(string message, string controllerInfo, ValidationType validationType)
        => (validationType switch
        {
            var x when x == ValidationType.Success || x == ValidationType.Information => new Action<string, string>(setInfo),
            ValidationType.Critical => setFatal,
            var x when x == ValidationType.Error || x == ValidationType.Exception => setError,
            ValidationType.Warning => setWarn,
            _ => (_, controllerInfo) => setError("invalid enum value", controllerInfo),
        })(message, controllerInfo);

标签: c#c#-8.0switch-expression

解决方案


switch 表达式期望您将从每个分支返回一些内容,但您正在尝试运行 void 方法。您可以让这些方法返回某些内容,使用常规开关,或者您可以返回Action<string, string>然后调用它,就像这样。

public void LogClientSideErrors(string message, ValidationType validationType)
    => (validationType switch
        {
            ValidationType.Success => new Action<string, string>(setInfo),
            ValidationType.Critical => setFatal,
            ValidationType.Error => setError,
            ValidationType.Exception => setError,
            ValidationType.Information => setInfo,
            ValidationType.Warning => setWarn,
            _ => (_, ci) => setError("invalid enum value", ci),
        })(message, controllerInfo);

推荐阅读