C#中的内联IF语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11982164/
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
Inline IF Statement in C#
提问by Landi
How will I write an Inline IF Statement in my C# Service class when setting my enum value according to what the database returned?
根据数据库返回的内容设置枚举值时,如何在 C# 服务类中编写内联 IF 语句?
For example: When the database value returned is 1 then set the enum value to VariablePeriods, when 2 then FixedPeriods.
例如:当返回的数据库值为 1 时,将枚举值设置为 VariablePeriods,当为 2 时,则设置为 FixedPeriods。
Hope you can help.
希望你能帮忙。
采纳答案by chiccodoro
The literal answer is:
字面的答案是:
return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:
请注意,内联 if 语句与 if 语句一样,只检查真假。如果 (value == 1) 的计算结果为 false,则不一定意味着 value == 2。因此,这样更安全:
return (value == 1
? Periods.VariablePeriods
: (value == 2
? Periods.FixedPeriods
: Periods.Unknown));
If you add more values an inline if will become unreadable and a switch would be preferred:
如果您添加更多值,则内联 if 将变得不可读,并且首选开关:
switch (value)
{
case 1:
return Periods.VariablePeriods;
case 2:
return Periods.FixedPeriods;
}
The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.
枚举的好处是它们有一个值,因此您可以使用映射的值,如 user854301 建议的那样。通过这种方式,您可以防止不必要的分支,从而使代码更具可读性和可扩展性。
回答by BugFinder
You can do inline ifs with
您可以使用内联 ifs
return y == 20 ? 1 : 2;
which will give you 1 if true and 2 if false.
如果为真,则为 1,如果为假,则为 2。
回答by user854301
You may define your enumlike so and use castwhere needed
你可以定义你enum喜欢的,并在需要的地方 使用cast
public enum MyEnum
{
VariablePeriods = 1,
FixedPeriods = 2
}
Usage
用法
public class Entity
{
public MyEnum Property { get; set; }
}
var returnedFromDB = 1;
var entity = new Entity();
entity.Property = (MyEnum)returnedFromDB;
回答by Davio
Enum to int: (int)Enum.FixedPeriods
枚举到整数: (int)Enum.FixedPeriods
Int to Enum: (Enum)myInt
整数到枚举: (Enum)myInt
回答by h1ghfive
This is what you need : ternary operator, please take a look at this
这就是你需要的:三元运算符,请看看这个
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx

