在C#转换布尔表达式为CHAR [英] Converting bool expression to char in c#
问题描述
我通过.NET测验,当我遇到类似下面一个问题。
I passed .NET quiz, when I met a question like below one.
Char ch = Convert.ToChar('a' | 'e' | 'c' | 'a');
在控制台中,我们可以看到,输出 CH
变量先按g
。
In console we can see that output for ch
variable is g
.
有人能描述一下是怎么回事?
谢谢!
Can someone describe what is happening ? Thanks!
推荐答案
这是不是它看起来像在第一的位置。正是在这些字符
的 INT
表示多个二进制计算的:
This is not what it looks like at first spot. It is more of binary calculations on the int
representation of these Char
:
下面是一个完整的文章举例说明这一点:的文章
Here is a full article explaining this with examples: Article
因此,对于按位或
二进制结果'A'| 'E'| C| 'A'
是 103
。如果转换为字符,这是先按g
So the binary result for the bitwise Or
of these 'a' | 'e' | 'c' | 'a'
is 103
. If you Convert that to Char, it is g
编辑:
我看到这个答案花了更多的关注比我虽然它应该得到更多的细节。
I see this answer took more attention than I though it deserves more details.
有从CHAR的隐式转换为int( INT I ='A'
编译),那么什么编译器实际上做是:
There is an implicit conversion from char to int (int i = 'a'
compiles), so what the compiler actually does is:
Convert.ToChar((int)'a' | (int)'e' | (int)'c' | (int)'a');
由于这些都是硬编码值,编译器做更多的工作:
Since these are hard-coded values, the compiler does more work:
Convert.ToChar(97 | 101 | 99 | 97);
和最后:
Convert.ToChar(103); // g
如果这些人不是硬编码值:
private static char BitwiseOr(char c1, char c2, char c3, char c4)
{
return Convert.ToChar(c1 | c2 | c3 | c4);
}
使用罗斯林您可以:
Using Roslyn you get:
private static char BitwiseOr(char c1, char c2, char c3, char c4)
{
return Convert.ToChar((int)c1 | c2 | c3 | c4);
}
转换为IL (或
使用(位)IL指令):
Converted to IL (or
(Bitwise) IL instruction used):
.method private hidebysig static char BitwiseOr(char c1,
char c2,
char c3,
char c4) cil managed
{
//
.maxstack 2
.locals init (char V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: or
IL_0004: ldarg.2
IL_0005: or
IL_0006: ldarg.3
IL_0007: or
IL_0008: call char [mscorlib]System.Convert::ToChar(int32)
IL_000d: stloc.0
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: ret
} // end of method Program::BitwiseOr
这篇关于在C#转换布尔表达式为CHAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!