windows 如何在最高位设置的注册表中放入 DWORD

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6608400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:19:33  来源:igfitidea点击:

How to put a DWORD in the registry with the highest bit set

c#windowstypesregistry

提问by Andreas Baus

I've run into a strange problem: when setting values of the DWORD type in the Windows Registry from my C# application, I keep getting errors when the highest bit is set. Apparently there seems to be some kind of conversion problem between signed and unsigned integers.

我遇到了一个奇怪的问题:从我的 C# 应用程序在 Windows 注册表中设置 DWORD 类型的值时,我在设置最高位时不断收到错误消息。显然,有符号和无符号整数之间似乎存在某种转换问题。

Example: when I do something like this

示例:当我做这样的事情时

regKey.SetValue("Value", 0x70000000u, RegistryValueKind.DWord);

it works fine. But when I add the highest bit (which, since I'm specifically dealing with unsigned integers, should be just another value bit), like this

它工作正常。但是当我添加最高位时(因为我专门处理无符号整数,所以应该只是另一个值位),像这样

regKey.SetValue("Value", 0xf0000000u, RegistryValueKind.DWord);

I get an exception ("The type of the value object did not match the specified RegistryValueKind or the object could not be properly converted").

我收到一个异常(“值对象的类型与指定的 RegistryValueKind 不匹配或对象无法正确转换”)。

But shouldn't it work? DWORD is an unsigned 32-bit integer data type, and so is the 0xf0000000uliteral (C# automatically assigns it the UInt32 datatype), so they should be a perfect match (and setting the value manually in the registry editor to "0xf0000000" works fine, too). Is this a bug in .NET or am I doing something wrong?

但它不应该工作吗?DWORD 是无符号的 32 位整数数据类型,0xf0000000u文字也是(C# 自动为其分配 UInt32 数据类型),因此它们应该是完美匹配(并且在注册表编辑器中手动将值设置为“0xf0000000”可以正常工作,也)。这是 .NET 中的错误还是我做错了什么?

回答by Jon Skeet

My guessis that you need to use a signed intinstead. So just convert it like this:

我的猜测是您需要使用签名int来代替。所以只需像这样转换它:

regKey.SetValue("Value", unchecked((int) 0xf0000000u),
                RegistryValueKind.DWord);

I agree it's a bit odd, when you consider that DWORD is normally unsigned (IIRC) but it's at least worth a try...

我同意这有点奇怪,当您认为 DWORD 通常是无符号 (IIRC) 但至少值得一试...

回答by MHollis

I know this is crazy late, however, if you don't want to use unchecked or are using VB.Net where it's not available then the following would work as well.

我知道这太晚了,但是,如果您不想使用 unchecked 或正在使用不可用的 VB.Net,那么以下方法也可以使用。

Byte[] byteArray = BitConverter.GetBytes(0xf0000000u);
int USignedIntTooBigForInt = BitConverter.ToInt32(byteArray, 0);
regKey.SetValue("Value", USignedIntTooBigForInt, RegistryValueKind.DWord);