【发布时间】: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
如果我必须在 C# 中将 bool 转换为 int,以下两个选项中哪个更快更高效?
int x = Convert.ToInt32(someBool);
或者
int x = someBool ? 1 : 0;
【问题讨论】:
标签: c# .net int boolean ternary-operator
如果你反汇编Convert.ToInt32(bool value)你会看到它是如何实现的:
public static int ToInt32(bool value)
{
return value ? 1 : 0;
}
参考:https://referencesource.microsoft.com/#mscorlib/system/convert.cs,d75d8ee9b3529289
【讨论】: