【问题标题】:Which is Faster and More Efficient: Convert.ToInt32() or Ternary Operator?哪个更快更高效:Convert.ToInt32() 还是三元运算符?
【发布时间】:2019-11-13 15:06:03
【问题描述】:

如果我必须在 C# 中将 bool 转换为 int,以下两个选项中哪个更快更高效?

int x = Convert.ToInt32(someBool);

或者

int x = someBool ? 1 : 0;

【问题讨论】:

标签: c# .net int boolean ternary-operator


【解决方案1】:

如果你反汇编Convert.ToInt32(bool value)你会看到它是如何实现的:

public static int ToInt32(bool value)
{
    return value ? 1 : 0;
}

参考:https://referencesource.microsoft.com/#mscorlib/system/convert.cs,d75d8ee9b3529289

【讨论】:

  • 啊!完美的!感谢您在我正要询问时添加参考,以便下次我可以自己查找内容?
猜你喜欢
  • 2020-07-22
  • 2011-06-10
  • 2011-04-01
  • 1970-01-01
  • 2016-02-10
  • 2020-06-18
  • 2010-12-12
  • 2013-03-31
  • 1970-01-01
相关资源
最近更新 更多