gpt4 book ai didi

C# 在 C++ 中使用 & 执行按位运算

转载 作者:太空狗 更新时间:2023-10-29 19:42:08 25 4
gpt4 key购买 nike

无论如何,这是我的问题,我一直在修改整个 C++ 程序以在 C# 中工作,我几乎完成了,我在 C++ 程序中有这个 If 语句。

if(info[i].location & 0x8 || 
info[i].location & 0x100||
info[i].location & 0x200)
{
//do work
}
else
{
return
}

当然,当我在 C# 中执行此操作时,它会给我一个“运算符‘||’不能应用于 'int' 和 'int' 类型的操作数”错误。

关于我的问题的任何线索,我猜 C# 有办法做到这一点,因为我对这些旧的 C 运算符相当不熟悉。

最佳答案

为什么会失败

从根本上讲,它的区别与此相同:

if (someInteger) // C or C++

对比

if (someInteger != 0) // C#

基本上,当涉及到逻辑运算符和条件时,C# 要严格得多 - 它会强制您使用 bool 的东西。或转换为 bool .

顺便说一句,这也是为什么在 C# 中这不仅仅是一个警告,而是一个全面的错误:

int x = ...;
if (x = 10) // Whoops - meant to be == but it's actually an assignment

如果您以这种方式进行比较:

if (10 == x)

这是通常开发人员试图避免像上面这样的拼写错误 - 但在 C# 中不需要它,除非您真的与常量 bool 进行比较值(value)观。

解决问题

我怀疑你只需要:

if (((info[i].location & 0x8) != 0)) ||
((info[i].location & 0x100) != 0)) ||
((info[i].location & 0x200) != 0)))

您可能不需要所有这些括号...但另一种选择是只使用一个测试:

if ((info[i].location & 0x308) != 0)

毕竟,您只是在测试这三个位中的任何一个是否已设置...

您还应该考虑使用基于标志的枚举:

[Flags]
public enum LocationTypes
{
Foo = 1 << 3; // The original 0x8
Bar = 1 << 8; // The original 0x100
Baz = 1 << 9; // The original 0x200
}

然后你可以使用:

LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if ((info[i].location) & mask != 0)

或使用 Unconstrained Melody :

LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if (info[i].location.HasAny(mask))

关于C# 在 C++ 中使用 & 执行按位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11785725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com