简体   繁体   English

C#UInt vs Cpp DWORD与负值冲突

[英]C# UInt vs Cpp DWORD conflict with negative values

C++: DWORD dwState = (DWORD)-1; C ++: DWORD dwState = (DWORD)-1;

Here there is no issues. 这里没有问题。

C#: uint state = -1 ; C#: uint state = -1 ;

Here, uint or UInt32 which is considered to be the equivalent of DWORD cannot have a negative value and it throws below exception. 在这里,与DWORD等效的uint或UInt32不能为负值,并且抛出以下异常。

Value was either too large or too small for a UInt32 对于UInt32,值太大或太小

I have a code which reads this value (which is stored in DB) both from cpp and c# programs. 我有一个代码可以从cpp和c#程序中读取此值(存储在DB中)。 Cpp marks invalid state as -1. Cpp将无效状态标记为-1。 Hence I'm unable to read it from C# front with uint type. 因此,我无法使用uint类型从C#前端读取它。 I cannot change this type in c++ program. 我无法在c ++程序中更改此类型。 Apart from -1, cpp may write any value between 0-65536 for variable. 除-1外,cpp可以为变量写入0-65536之间的任何值。

How can I handle it from C# front!? 我该如何从C#前端处理它?

How can I handle it from C# front!? 我该如何从C#前端处理它?

You can use the unchecked operator for the constant assignment: 您可以将unchecked运算符用于常量分配:

uint state = unchecked((uint) -1);

From the C# spec section 7.6.12: 在C#规范第7.6.12节中:

The checked and unchecked operators are used to control the overflow checking context for integral-type arithmetic operators and conversions. checkedunchecked运算符用于控制整数型算术运算符和转换的溢出检查上下文

... ...

For constant expressions (expressions that can be fully evaluated at compile time), the default overflow checking context is always checked . 对于常量表达式(可以在编译时完全评估的表达式),始终会checked默认的溢出检查上下文。 Unless a constant expression is explicitly placed in an unchecked context, overflows that occur during the compile-time evaluation of the expression always cause compile-time errors. 除非将常量表达式显式放置在unchecked上下文中,否则在表达式的编译时求值过程中发生的溢出始终会导致编译时错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM