c# - 构建字符串时如何保持上一行的缩进

标签 c# string

考虑以下示例。我用 ToString() 方法定义了一个结构

public struct InnerStruct
{
    public double a;
    public double b;

    public override string ToString()
    {
        return $"InnerStruct:\n" +
               $"    a: {a}\n" +
               $"    b: {b}";
    }
}

调用 ToString()

 var i = new InnerStruct(){a=1, b=2};
 i.ToString()
 @"InnerStruct:
     a: 1
     b: 2
 "

因此 ToString() 给出了一个漂亮且可读的字符串,其中 ab 缩进了四个空格。但是,假设我有一个新结构

public struct OuterStruct
{
    public double c;
    public InnerStruct inner;

    public override string ToString()
    {
        return $"OuterStruct:\n" +
               $"    c: {c}\n" +
               $"    inner: {inner.ToString()}";
    }
}

正在写作

var u = new OuterStruct(){c=3, inner=i};
u.ToString()
@"OuterStruct:
     c: 3
     inner: InnerStruct:
     a: 1
     b: 2
"

但这不是我想要的。换行符 \n 强制下一行从头开始并从那里算起四个空格。我要

@"OuterStruct:
     c: 3
     inner: InnerStruct:
         a: 1
         b: 2
"

即我希望内部结构成员的缩进相对于内部结构的缩进开始。有什么想法吗?

最佳答案

您可以添加一个指示深度的重载:

public override string ToString() 
{ 
    return ToString(0);
}

public string ToString(int depth)
{
    var spaces = new string(' ', 4 * depth);
    return $"InnerStruct:\n" +
           $"{spaces}    a: {a}\n" +
           $"{spaces}    b: {b}";
}

然后在打印这个内部结构时,传递深度:

$"    inner: {inner.ToString(1)}";

或者传递 ++depth 而不是 1,无论你想要哪个。

关于c# - 构建字符串时如何保持上一行的缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52110309/

相关文章:

c# - ReactiveUI - this.RaiseAndSetIfChanged

c# - MSWord 中的表格对齐

c# - 在 Entity Framework 中插入的最快方法

swift - 在 Swift 4 中添加到字符串

string - 生命周期如何作用于常量字符串/字符串文字?

php - 将 mysql 数据导出到 CSV 后出现数字问题

c# - 使用 C# 抓取 HTML

c# - MongoDB 查找方法返回类名

java - 输出包含结束 html 标签的行

java - 要么是菜鸟错误,要么是在java中误用.equals