有什么用\u和\x而代表字符文字之间的差异 [英] What is the difference between using \u and \x while representing character literal
问题描述
我所看到的 \u
和 \x
而代表字符文字在一些地方互换使用。
I have seen \u
and \x
used interchangeably in some places while representing a character literal.
例如'\\\©'=='\x00A9
计算结果为真正
难道我们不是应该只使用 \u
来表示Unicode字符?什么是使用具有两种方式来表示一个字符的?
Aren't we supposed to use only \u
to represent unicode character? What is the use of having two ways to represent a character?
推荐答案
我的强烈的唯一建议使用 \u
,因为它更容易出错。
I would strongly recommend only using \u
, as it's much less error-prone.
\x
消耗1-4个字符,只要它们是十六进制数字 - 而 \u
必须的总是的遵循4十六进制数字。从C#5规范,部分2.4.4.4,语法为 \x
:
\x
consumes 1-4 characters, so long as they're hex digits - whereas \u
must always be followed by 4 hex digits. From the C# 5 specification, section 2.4.4.4, the grammar for \x
:
的十六进制转义序列:的结果
   \x
的进制的进制的<子>选择的进制的<子>选择的进制的<子>选择
hexadecimal-escape-sequence:
\x
hex-digit hex-digitopt hex-digitopt hex-digitopt
因此,例如:
string good = "Tab\x9Good compiler";
string bad = "Tab\x9Bad compiler";
...看起来相似,但的非常的不同的字符串,因为后者有效地标签,然后按 U + 9BAD
其次是的编译器。
... look similar but are very different strings, as the latter is effectively "Tab" followed by U+9BAD
followed by " compiler".
我个人希望C#语言从来没有包括 \x
,但我们走了。
Personally I wish the C# language had never included \x
, but there we go.
请注意,有也 \U
,它总是跟着8个十六进制数字,主要用于非BMP字符。
Note that there's also \U
, which is always followed by 8 hex digits, primarily used for non-BMP characters.
有间<另外一个很大的区别code> \u 和 \x
:后者的只有 ,而 \u
也可以在标识中使用:
There's one other big difference between \u
and \x
: the latter is only used in character and string literals, whereas \u
can also be used in identifiers:
string x = "just a normal string";
Console.WriteLine(\u0078); // Still refers to the identifier x
这篇关于有什么用\u和\x而代表字符文字之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!