简体   繁体   中英

C# returning UInt32 vs Int32 - C# thinking 0 and 1 are Int32

I'm working on a C# dll bind to UDK, in which you have to return a unsigned 32 bit integer for bool values - hence 0 is false, anything greater is true. The UDK gets the value and converts it to either true or false...

I was doing some code and found this:

[DllExport("CheckCaps", CallingConvention = CallingConvention.StdCall)]
    public static UInt32 CheckCaps()
    {
        return ( Console.CapsLock ? 1 : 0);
    }

gave me the error of:

"Error, Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)"

While I understand the error, I didnt have this issue before doing

            if (File.Exists(filepath))
            return 1;
        else
            return 0;

From the way it looks like C#'s issue with string typecasting, where if you have this:

int example = 5;
Console.Writeline( example);
Console.Writeline( example + "");

The first console.writeline will give an error because C# won't autotype cast to a string

I understand that there are logical reasons behind these errors (as they occur in these situations) , but is there a fix for this other than doing Convert.ToUInt32(1) and Convert.ToUInt32(0)?

(I'm hoping for a fix akin to how you can go 0.f for floats, but for unsigned intergers)

The code below

if (File.Exists(filepath))
    return 1;
else
    return 0;

compiles because according to C# standard

13.1.7 A constant-expression (§14.16) of type int can be converted to type sbyte , byte , short , ushort , uint , or ulong , provided the value of the constant-expression is within the range of the destination type.

There is no implicit conversion like that defined for conditional expressions, so your first code snippet needs either an explicit cast or a U suffix:

return Console.CapsLock ? 1U : 0;

Note that only one conversion/suffix is necessary, because zero can be converted to uint based on the rule 13.1.7 above.

1u是1的无符号文字语法0u是0。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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