奇怪的字符串转换行为

时间:2016-06-02 14:25:10

标签: c#

在C#中,我有这个:

    public static readonly Char LeftBrkt = (char)171; // <<
    public static readonly Char RghtBrkt = (char)187; // >>

以及之后的这个:

        String fred = "Select";
        fred = LeftBrkt + RghtBrkt + fred + LeftBrkt + RghtBrkt;

并且,完成后,fred成为了这个:

358Select«»

现在,如果我使用以下任何一种方法,我可以绕过它:

        fred = LeftBrkt + (RghtBrkt + fred) + LeftBrkt + RghtBrkt;
        fred = LeftBrkt + "" + RghtBrkt + fred + LeftBrkt + RghtBrkt;

这听起来像编译错误还是我错过了什么?

5 个答案:

答案 0 :(得分:0)

这是因为字符内部只是一个整数。因此,操作p.then(function(data) { ... return Promise.delay(100); // wait 100ms before allowing promise chain to proceed }) 导致添加187到171.您希望在以下字符之前将字符转换为字符串:

LeftBrkt + RghtBrkt

如果你只写这个,这也会有用:

fred = LeftBrkt.ToString() + RghtBrkt.ToString() + fred + LeftBrkt.ToString() + RghtBrkt.ToString();

因为通过第一个操作数,编译器已经知道它应该在每个操作数上调用fred = LeftBrkt.ToString() + RghtBrkt + fred + LeftBrkt + RghtBrkt; - 方法

但最好使用ToString

String.Format

答案 1 :(得分:0)

您需要从Char转换为String:

fred = LeftBrkt.ToString() + RghtBrkt.ToString() + fred + LeftBrkt.ToString() + RghtBrkt.ToString();

答案 2 :(得分:0)

你没有&#34;错过了什么&#34;如果没有意识到使用+运算符,编译器会尝试做正确的事情 - 大部分时间都是正确的,但有时会出错。您需要更明确地了解您尝试做什么(连续字符串,而不是数字添加)。

表达式从左到右进行评估。当你执行char + char时,它采用整数值并以数字方式添加它们。执行int + string时,它会将int转换为其字符串表示形式并将它们连接起来。此后string + char还将char视为字符串并将其连接起来。

更明确地了解您想要的内容的最简单方法是使用String.ConcatString.Format

var result = String.Format("{0}{1}{2}{0}{1}", LeftBrkt, RgtBrkt, fred);

var result = String.Concat(LeftBrkt, RgtBrkt, fred, LeftBrkt, RgtBrkt);

答案 3 :(得分:0)

这很有趣。 .Net Char类型基本上是numberCharacter。所以

 fred = LeftBrkt + RghtBrkt + fred + LeftBrkt + RghtBrkt;

评估为

 fred = ((((LeftBrkt + RghtBrkt) + fred) + LeftBrkt) + RghtBrkt);

那是

 fred = ((((Character + Character) + string) + Character) + Character);

Character + Characterint,因为我们无法合并两个charecters

评估number + string号时自动转换为字符串。

答案 4 :(得分:0)

谢谢大家的有用和快速回复;我最终得到了这个:

LeftBrkt和RghtBrkt成了:

    public static readonly String LeftBrkt = ((char)171).ToString(); // <<
    public static readonly String RghtBrkt = ((char)187).ToString(); // >>