本文介绍了内联IF语句在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何IF在我的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?

例如:当数据库值返回的是1,那么枚举值设置为VariablePeriods,当2然后FixedPeriods。

For example: When the database value returned is 1 then set the enum value to VariablePeriods, when 2 then FixedPeriods.

希望能对你有所帮助。

推荐答案

字面?答案是:

return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);

请注意,内联if语句,就像if语句,只为真或假支票。如果(价值== 1)计算为false,它可能并不一定意味着价值== 2,因此,会是这样更安全:

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:

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;
}



有关枚举的好处是,他们有一个值,所以你可以使用该映射的值,user854301建议。这种方式可以防止不必要的分支从而使代码的可读性和可扩展性。

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.

这篇关于内联IF语句在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:57