用等效字符串表示Char

时间:2012-01-03 11:34:37

标签: c# string formatting char

我将以下类作为ListBox的DataSource

class SeparatorChars
{
    /// <summary>
    /// Text to describe character
    /// </summary>
    public string Text { get; set; }

    /// <summary>
    /// Char value of the character
    /// </summary>
    public char Value { get; set; }

    /// <summary>
    /// Represent object as string
    /// </summary>
    /// <returns>String representing object</returns>
    public override string ToString()
    {
        return Text + " '" + Value + "'";
    }
}

问题是,默认情况下,这将使用Value作为添加到字符串的常规字符,例如,如果我为Tab定义此类,则:

var TabSeparator = new SeparatorChars {Text = "Tab", Value = '\t'}

字符串表示形式为:

Tab '     '

但我需要它

Tab '\t'

怎么做?!

2 个答案:

答案 0 :(得分:6)

不可否认,大多数是从this post撕掉并未经测试。

public override string ToString()
{
    return ToLiteral(Text + " '" + Value + "'");
}

private string ToLiteral(string input)
{
    var writer = new StringWriter();
    CSharpCodeProvider provider = new CSharpCodeProvider();
    provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
    return writer.ToString();
}

答案 1 :(得分:4)

这是一篇博客文章,其中包含一些示例代码:Mark Gu: Escape Sequences in C#