简体   繁体   English

C#中的内联IF语句

[英]Inline IF Statement in C#

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#Service类中编写内联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. 希望你能帮忙。

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语句与if语句一样,只检查true或false。 If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this: 如果(value == 1)求值为false,则可能不一定意味着值== 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: 如果您添加更多值内联,如果将变得不可读并且首选开关:

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. 关于枚举的好处是它们有一个值,因此您可以使用映射的值,如user854301所建议的那样。 This way you can prevent unnecessary branches thus making the code more readable and extensible. 这样就可以防止不必要的分支,从而使代码更具可读性和可扩展性。

You may define your enum like so and use cast where needed 您可以像这样定义enum ,并在需要时使用强制转换

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;

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。

Enum to int: (int)Enum.FixedPeriods 枚举到int: (int)Enum.FixedPeriods

Int to Enum: (Enum)myInt Int to Enum :( (Enum)myInt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM