Nag*_*far 32 c# action if-statement
我想做一行if语句有多于1个动作.
默认是这样的:
(if) ? then : else
userType = (user.Type == 0) ? "Admin" : "User";
Run Code Online (Sandbox Code Playgroud)
但我不需要"别的",我需要一个"别的如果"
像多行中那样:
if (user.Type == 0)
userType = "Admin"
else if (user.Type == 1)
userType = "User"
else if (user.Type == 2)
userType = "Employee"
Run Code Online (Sandbox Code Playgroud)
单线有可能吗?
Jon*_*eet 77
听起来你真的想要Dictionary<int, string>或者可能是switch声明......
您可以使用条件运算符执行此操作:
userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";
Run Code Online (Sandbox Code Playgroud)
虽然你可以把它放在一行,但我强烈建议你不要这样做.
我通常只会针对不同的条件执行此操作 - 不仅仅是几个不同的可能值,这在地图中可以更好地处理.
小智 18
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩.
你可以用单行写出来,但这不是别人能读的东西.保持它就像你已经写过它,它本身就已经很美了.
如果你有太多的if/else结构,你可能会考虑使用不同的数据结构,如Dictionaries(查找键)或Collection(运行条件LINQ查询)