C#数字常量 [英] C# numeric constants

查看:144
本文介绍了C#数字常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C#代码:

byte rule = 0;
...
rule = rule | 0x80;

会产生错误:


无法将类型int隐式转换为byte。存在显式转换(您缺少转换吗?)

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

[更新:问题的第一个版本错误。 ..我误解了编译器输出]

[Update: first version of the question was wrong ... I misread the compiler output]

添加转换不能解决问题:

rule = rule | (byte) 0x80;

我需要写为:

rule |= 0x80;

这看起来很奇怪。为什么 | = 运算符与 | 运算符不同?

Which just seems weird. Why is the |= operator any different to the | operator?

有没有其他方法告诉编译器将常量视为一个字节?

Is there any other way of telling the compiler to treat the constant as a byte?

@ Giovanni Galbo :yes和no。该代码处理外部设备中闪存的编程,并且逻辑上表示单个字节的存储器。我可以把它以后,但这似乎更明显。我想我的C遗产已经过了太多了!

@ Giovanni Galbo : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!

@ Jonathon Holland :'as'语法看起来更整洁, to work ...它产生:

@ Jonathon Holland : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:


as操作符必须使用引用类型或可空类型是不可为空值的类型)

The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)


推荐答案

int rule = 0;
rule |= 0x80;

http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx The |运算符为所有值类型定义。我认为这将产生预期的结果。 | =运算符是一个或然后的assign运算符,它只是rule = rule |的简写0x80。

http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx The | operator is defined for all value types. I think this will produced the intended result. The "|=" operator is an or then assign operator, which is simply shorthand for rule = rule | 0x80.

关于C#的一个更新的事情是它可以让你做疯狂的事情像滥用价值类型只是基于他们的大小。一个'int'与一个字节完全相同,除非编译器会引发警告,如果你尝试并同时使用它们。简单地坚持一个(在这种情况下,int)工作得很好。如果你担心64bit准备就绪,你可以指定int32,但是所有的int都是int32s,甚至以x64模式运行。

One of the niftier things about C# is that it lets you do crazy things like abuse value types simply based on their size. An 'int' is exactly the same as a byte, except the compiler will throw warnings if you try and use them as both at the same time. Simply sticking with one (in this case, int) works well. If you're concerned about 64bit readiness, you can specify int32, but all ints are int32s, even running in x64 mode.

这篇关于C#数字常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆