You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中能否在switch/if语句中直接引用求值表达式而无需先赋值?

问题描述

现有如下代码:

public async Task<IActionResult> Weather(string cityName)
{
    if (cityName == null)
    {
        return View(await _weatherService.GetWeather(cityName));
    }
    return RedirectToAction("Weather");
}

希望重构为使用switch语句对await _weatherService.GetWeather(cityName)的求值结果进行判断,且无需提前将结果赋值给变量,直接在case分支中引用该结果,询问是否可行,还是必须提前赋值。

目前已实现的写法(需提前赋值):

WeatherConvertedObject w = await _weatherService.GetWeather(cityName);
switch (w)
{
    case null: return RedirectToAction("Weather");
    case not null: return View(await _weatherService.GetWeather(cityName));
}

期望的写法(示意代码,无法编译):

switch (await _weatherService.GetWeather(cityName))
{
    case null: return RedirectToAction("Weather");
    case not null: return View(this);
        //此处仅为示意,代表引用求值后的对象
}
解决方案

完全可以实现,无需提前赋值变量。利用C#的模式绑定特性,switch表达式会对await _weatherService.GetWeather(cityName)求值一次,再通过case分支绑定变量直接引用结果,同时还能避免你当前写法里重复调用服务的性能问题。

写法一:类型匹配绑定变量

switch (await _weatherService.GetWeather(cityName))
{
    case null:
        return RedirectToAction("Weather");
    case WeatherConvertedObject w:
        return View(w);
}

写法二:not null模式绑定变量

switch (await _weatherService.GetWeather(cityName))
{
    case null:
        return RedirectToAction("Weather");
    case not null var w:
        return View(w);
}

写法三:switch表达式简化版

如果逻辑更简单,还可以用switch表达式进一步精简代码:

return await _weatherService.GetWeather(cityName) switch
{
    null => RedirectToAction("Weather"),
    var w => View(w)
};

内容的提问来源于stack exchange,提问作者Aleksandar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:37:34