gpt4 book ai didi

c# - 如何在 C# 中减去一行中的字节

转载 作者:太空狗 更新时间:2023-10-29 22:14:56 25 4
gpt4 key购买 nike

这真的很奇怪。谁能解释一下?

此代码无效:

const byte ASC_OFFSET = 96;
string Upright = "firefly";
byte c7 = (byte)Upright[6] - ASC_OFFSET;
//Cannot implicitly convert type 'int' to 'byte'.

此代码也不起作用:

const byte ASC_OFFSET = 96;
string Upright = "firefly";
byte c7 = (byte)Upright[6] - (byte)ASC_OFFSET;
//Cannot implicitly convert type 'int' to 'byte'.

然而,将减法放在单独的一行上效果很好:

const byte ASC_OFFSET = 96;
string Upright = "firefly";
byte c7 = (byte)Upright[6];
c7 -= ASC_OFFSET;

如果必须的话,我不介意将语句放在不同的行中......但我不得不怀疑......

为什么?

最佳答案

这是因为 1) byte 操作导致 int(请参阅此处的原因:http://blogs.msdn.com/b/oldnewthing/archive/2004/03/10/87247.aspx)和 2) 以下 C# 代码

c7 -= ASC_OFFSET;

会在后台“神奇地”编译成

c7 = (byte)(c7 - ASC_OFFSET);

这在 C# 规范中有明确记录:http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf

14.14.2 Compound assignment:

An operation of the form x op= y is processed by applying binary operator overload resolution (§14.2.4) as if the operation was written x op y. Then,

• If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, except that x is evaluated only once.

Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

• Otherwise, the compound assignment is invalid, and a compile-time error occurs

关于c# - 如何在 C# 中减去一行中的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4577560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com