我想知道是否有任何方法来声明一个字节变量在一个简短的方式,如浮动或双精度?我指的是5f和5d。当然,我可以写字节x = 5,但如果你用var表示局部变量,那就有点无关紧要了。


当前回答

从这个MSDN页面,似乎你唯一的选择是显式强制转换(var x =(字节)5),或停止使用var…

其他回答

根据MSDN,您可以使用十进制,十六进制或二进制文字来声明一个字节。

// decimal literal
byte x = 5;

// hex decimal literal
byte x = 0xC5;

// binary literal
byte x = 0b0000_0101;

So, we added binary literals in VB last fall and got similar feedback from early testers. We did decide to add a suffix for byte for VB. We settled on SB (for signed byte) and UB (for unsigned byte). The reason it's not just B and SB is two-fold. One, the B suffix is ambiguous if you're writing in hexadecimal (what does 0xFFB mean?) and even if we had a solution for that, or another character than 'B' ('Y' was considered, F# uses this) no one could remember whether the default was signed or unsigned - .NET bytes are unsigned by default so it would make sense to pick B and SB but all the other suffixes are signed by default so it would be consistent with other type suffixes to pick B and UB. In the end we went for unambiguous SB and UB. -- Anthony D. Green,

https://roslyn.codeplex.com/discussions/542111

显然,他们已经在VB中完成了这个动作。NET(可能现在还没有发布),他们可能会在roslyn中为c#实现它——如果你认为这是你喜欢的东西,去投票吧。您还可以提出一种可能的语法。

从这个MSDN页面,似乎你唯一的选择是显式强制转换(var x =(字节)5),或停止使用var…

在MSDN中没有提到字节的字面值后缀,在c# 4.0语言规范中也是如此。c#中唯一的文字后缀是整数和实数,如下所示:

u = uint
l = long
ul = ulong
f = float
m = decimal
d = double

如果你想使用var,你总是可以将字节转换为var y = (byte) 5

虽然不是真正相关的,但在c# 7中,引入了一个新的二进制前缀0b,它表示数字是二进制格式的。但是仍然没有后缀使它成为一个字节,例如:

var b = 0b1010_1011_1100_1101_1110_1111; //int