简体   繁体   English

如何将 bool 转换为 int?

[英]How can I convert from a bool to an int?

My code looks like this:我的代码如下所示:

if (Settings.adp == true)
   App.DB.UpdateIntSetting(SET.Adp, 0);
else
   App.DB.UpdateIntSetting(SET.Adp, 1);

Is there a way I could get this down to one line by somehow converting the bool Settings.adp into an int (0 or 1)有没有办法通过某种方式将 bool Settings.adp 转换为 int(0 或 1)

You can use the ternary operator to consolidate it to one line:您可以使用三元运算符将其合并为一行:

App.DB.UpdateIntSetting(SET.Adp, Settings.adp ? 0 : 1);

From the documentation文档

condition?健康)状况? consequence: alternative结果:替代

With your reversed logic, Nathan's ternary operator answer is probably the best option for clarity, but you could also use Convert.ToInt32 :使用您的反向逻辑,Nathan 的三元运算符答案可能是清晰的最佳选择,但您也可以使用Convert.ToInt32

bool negatedValue = !Settings.adp;
App.DB.UpdateIntSetting(SET.Adp, Convert.ToInt32(negatedValue));

Try it online在线试用

Your situation looks like a good candidate for using ValueObject , provided that you need to perform that conversion to int in many places in your project.您的情况看起来很适合使用ValueObject ,前提是您需要在项目的许多地方执行到 int 的转换。

Reason: If you are not using ValueObject you will end up duplicating that logic for conversion to int all over your application.原因:如果您不使用 ValueObject,您最终将在整个应用程序中复制转换为 int 的逻辑。 And ValueObject is even more suited for your case because of your inverted logic (true -> 0, false -> 1).由于您的倒置逻辑(true -> 0,false -> 1),ValueObject 更适合您的情况。 Using ValueObject will help you avoid duplication of this logic.使用 ValueObject 将帮助您避免重复此逻辑。

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

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