gpt4 book ai didi

c# - 具有 2 个操作的单行 if 语句

转载 作者:IT王子 更新时间:2023-10-29 04:10:04 30 4
gpt4 key购买 nike

我想在单行 if 语句中包含多个操作。

默认是这样的:

(if) ? then : else

userType = (user.Type == 0) ? "Admin" : "User";

但我不仅需要一个“else”,我还需要一个“else if”

像多行一样:

if (user.Type == 0)
userType = "Admin"
else if (user.Type == 1)
userType = "User"
else if (user.Type == 2)
userType = "Employee"

单行有可能吗?

最佳答案

听起来你真的想要一个 Dictionary<int, string>或者可能是 switch声明...

不过您可以使用条件运算符来做到这一点:

userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";

虽然您可以将其放在一行中,但我强烈建议您不要这样做。

不过,我通常针对不同的条件执行此操作 - 而不仅仅是几个不同的可能值,这在 map 中处理得更好。

关于c# - 具有 2 个操作的单行 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12484133/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com