我最近在@edplunkett看到了这段代码,并认为这对我正在做的事情有用,但是我想修改为包含缩进:
static void Main()
{
var randomCrap = new List<Object>
{
1, "two",
new List<object> { 3, 4 },
5, 6,
new List<object> {
new List<object> { 7, 8, "nine" },
},
};
randomCrap.PrintAll();
}
public static class Extensions
{
public static void PrintAll(this Object root)
{
foreach (var x in root.SelectAll())
{
Console.WriteLine(x);
}
}
public static IEnumerable<Object> SelectAll(this object o)
{
// Thank you, eocron
if (o is String)
{
yield return o;
}
else if (o is IEnumerable)
{
var e = o as IEnumerable;
foreach (var child in e)
{
foreach (var child2 in child.SelectAll())
yield return child2;
}
}
else
{
yield return o;
}
}
}
每次遇到IEnumerable
时添加缩进是多么容易,这样你就可以得到:
1
two
3
4
5
6
7
8
nine
类似于0的起始缩进,每遇到IEnumerable
会增加一个?
答案 0 :(得分:0)
那将是一个很大的变化。现在,它传递给Function,并从中返回单个对象。你必须改变它来传递和返回两件事:eobject和缩进级别。它可以做到,但会破坏@ edplunkett设计的优雅。
更新:实际上,对于Tuples来说,它毕竟不是那么糟糕::
static void Main()
{
var randomCrap = new List<Object>
{
1, "two",
new List<object> { 3, 4 },
5, 6,
new List<object> {
new List<object> { 7, 8, "nine" },
},
};
randomCrap.PrintAll();
}
public static class Extensions
{
public static void PrintAll(this Object root)
{
foreach (var x in root.SelectAll(0))
{
Console.WriteLine("{0}{1}", new string('_', x.indent),x.obj);
}
}
public static IEnumerable<(Object obj,int indent)>
SelectAll(this object o, int indent)
{
// Thank you, eocron
if (o is String)
{
yield return (o,indent);
}
else if (o is IEnumerable)
{
var e = o as IEnumerable;
foreach (var child in e)
{
foreach (var child2 in child.SelectAll(indent+1))
yield return child2;
}
}
else
{
yield return (o, indent);
}
}
}
答案 1 :(得分:0)
您可以使用元组轻松完成:
public static class Extensions
{
public static void PrintAll(this Object root)
{
foreach (var x in root.SelectAll(""))
{
Console.WriteLine(x.Item1 + x.Item2);
}
}
public static IEnumerable<(string, Object)> SelectAll(this object o, string indentation)
{
// Thank you, eocron
if (o is String)
{
yield return (indentation, o);
}
else if (o is IEnumerable)
{
var e = o as IEnumerable;
foreach (var child in e)
{
foreach (var child2 in child.SelectAll(indentation + " "))
yield return (child2.Item1, child2.Item2);
}
}
else
{
yield return (indentation, o);
}
}
}
编辑:这是一个前C#7版本(未经测试,但应该有效):
public static class Extensions
{
public static void PrintAll(this Object root)
{
foreach (var x in root.SelectAll(""))
{
Console.WriteLine(x.Item1 + x.Item2);
}
}
public static IEnumerable<Tuple<string, Object>> SelectAll(this object o, string indentation)
{
// Thank you, eocron
if (o is String)
{
yield return Tuple.Create(indentation, o);
}
else if (o is IEnumerable)
{
var e = o as IEnumerable;
foreach (var child in e)
{
foreach (var child2 in child.SelectAll(indentation + " "))
yield return Tuple.Create(child2.Item1, child2.Item2);
}
}
else
{
yield return Tuple.Create(indentation, o);
}
}
}