C# 具有 2 个操作的单行 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12484133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Single line if statement with 2 actions
提问by Nagelfar
I'd like to do a single line if statement with more than 1 action.
我想用超过 1 个动作的单行 if 语句。
Default is this:
默认是这样的:
(if) ? then : else
userType = (user.Type == 0) ? "Admin" : "User";
But I don't need an "else" only, I need an "else if"
但我不需要一个“else”,我需要一个“else if”
like that in multi line:
就像在多行中那样:
if (user.Type == 0)
userType = "Admin"
else if (user.Type == 1)
userType = "User"
else if (user.Type == 2)
userType = "Employee"
Is there a possibility for that in single line?
在单行中是否有可能?
采纳答案by Jon Skeet
Sounds like you really want a Dictionary<int, string>or possibly a switchstatement...
听起来你真的想要一个Dictionary<int, string>或可能是一个switch声明......
You cando it with the conditional operator though:
不过,您可以使用条件运算符来做到这一点:
userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";
While you couldput that in one line, I'd strongly urge you not to.
虽然您可以将其放在一行中,但我强烈建议您不要这样做。
I would normally onlydo this for different conditions though - not just several different possible values, which is better handled in a map.
我通常只会在不同的条件下执行此操作 - 而不仅仅是几个不同的可能值,这在地图中更好地处理。
回答by Tigran
You canwrite that in single line, but it's not something that someone would be able to read. Keep it like you already wrote it, it's already beautiful by itself.
您可以将其写成一行,但这不是某人能够阅读的内容。保持它就像你已经写的那样,它本身已经很漂亮了。
If you have too much if/elseconstructs, you may think about using of different datastructures, like Dictionaries(to look up keys) or Collection(to run conditional LINQqueries on it)
如果您有太多的if/else构造,您可能会考虑使用不同的数据结构,例如Dictionaries(查找键)或Collection(对其运行条件LINQ查询)
回答by Tigran
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
应该做的伎俩。

