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

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

问题描述

我有以下的C#代码:

 字节规则= 0; 
...
规则=规则| 0x80的;



产生错误:




无法隐式转换类型'诠释'到'字节'。一个显式转换存在(是否缺少强制转换?)




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



添加投的解决问题:

 规则=规则| (字节)0x80的; 



我需要把它写成:

 规则| = 0x80的; 



刚刚似乎不可思议。为什么 | = 运营商有什么不同的 | 运营商



有没有告诉编译器把常量作为一个字节的任何其他方式?






@乔瓦尼Galbo :yes和no。代码处理该闪速存储器的编程中的外部设备,并逻辑上表示的存储器中的单个字节。后来我才可以投,但是这似乎更加明显。 !我想我的C遗产经历了太多展示



@乔纳森·荷兰:在'为'语法看起来整洁但遗憾的是没有出现工作... ...它产生:




as运算符必须用引用类型或可空类型(字节使用是一个非空的值类型)



解决方案

  INT规则= 0; 
规则| = 0x80的;

http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx 的|运营商为所有的值类型定义。我认为这将产生预期的结果。该| =运算符是一个或然后分配给运营商,这简直是对规则=规则速记| 0x80的。



一个关于C#的niftier事情之一是,它可以让你做疯狂的事情像滥用值类型简单地根据它们的大小。一个'诠释'是完全一样的一个字节,除了编译器将抛出警告,如果你试图在同一时间使用它们两者。简单地具有一个伸出(在这种情况下,INT)效果很好。如果你担心64位的准备,您可以指定INT32,但所有的整数都int32s,即使是在64位模式下运行。


I have the following C# code:

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

which produces the error:

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]

Adding the cast doesn't fix the problem:

rule = rule | (byte) 0x80;

I need to write it as:

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 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 : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:

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 | 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.

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天全站免登陆