C# 中烦人的强制转换

发布于 2024-12-08 21:39:39 字数 739 浏览 3 评论 0原文

我一直在用 C# 编写一个相当低级的应用程序,它使用大量字节短路和位操作。我注意到的一件事是,C# 不喜欢对除整数以外的任何内容进行位操作和使用布尔运算符。这导致我的代码中出现了数百次强制转换。诸如“无法将类型‘int’隐式转换为‘ushort’之类的错误。存在显式转换(是否缺少强制转换?)”

byte b1 = 0x22;
byte b2 = 0x33;
ushort s1 = b1 << 8; // <-- Error Here
ushort s2 = s1 | b2; // <-- And Here

这迫使我在任何地方都使用强制转换。

byte b1 = 0x22;
byte b2 = 0x33;
ushort s1 = (ushort)(b1 << 8 | b2);

这最多应该是一个警告。即使 b1 和 b2 的类型为 ushort,它仍然是一个错误。即使是加法等基本算术也会产生相同的错误。

ushort s1 = 0x22;
ushort s2 = s1 + 0x11; // <-- Oh Come On.
ushort s3 = 8;
ushort s4 = (s1 << s3 | s2); // <-- Still an Error.

无论如何,还是我必须接受这样一个事实:在使用除整数以外的任何内容时,强制转换只是 C# 生活的一部分,或者只使用 C++,这不是问题。

I have been writing a rather low level application in C# that uses a lot of bytes shorts and bit manipulation. One thing I noticed is that C# doesn't like to do bit manipulation and use boolean operators on anything other than ints. This has resulted in 100's of casts all over my code. Errors such as "Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)"

byte b1 = 0x22;
byte b2 = 0x33;
ushort s1 = b1 << 8; // <-- Error Here
ushort s2 = s1 | b2; // <-- And Here

This forces me to use casts everywhere.

byte b1 = 0x22;
byte b2 = 0x33;
ushort s1 = (ushort)(b1 << 8 | b2);

This should at most be a warning. Even if b1 and b2 where of type ushort it is still an error. Even basic arithmetic such as addition gives the same error.

ushort s1 = 0x22;
ushort s2 = s1 + 0x11; // <-- Oh Come On.
ushort s3 = 8;
ushort s4 = (s1 << s3 | s2); // <-- Still an Error.

Is there anyway around this or do I just have to resign myself to the fact that casts are just a part of C# life when it comes to using anything other than integers or just use C++ where this is not a problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小情绪 2024-12-15 21:39:39

如果您查看调试器中的本机代码,您会发现几乎所有这些算术都是以整数形式完成的。我得出的结论是,最好的办法是在我的代码中反映这一点,对局部变量使用整数,并仅在将值复制到我的数据结构中时进行转换。

If you look at the native code in the debugger, you see that pretty much all of this arithmetic is done as ints anyway. I've come to the conclusion that the best thing to do is reflect this in my code by using ints for locals and casting only when copying the value into my data structure.

幼儿园老大 2024-12-15 21:39:39

不幸的是,没有办法解决这个问题。这就是语言的设计方式(事实上,它比语言更深入,并深入到 CLR 其中所有按位逻辑都作为 Int32 数据类型执行)。

您可以继续进行转换,创建包装函数/类,或者切换到不安全/C++ 代码并在那里执行。

Unfortunately there is no way around this. It is just how the language was designed (and in fact it goes deeper than the language and into the CLR where all bit-wise logic is performed as Int32 data types).

You can either keep doing the casts, create wrapper functions/classes or switch to unsafe/C++ code and do it in there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文