我有一个实用程序方法来处理字符串集合,比如说:
public static string MyJoin(this IEnumerable<string> strings)
{
return string.Join(Environment.NewLine, strings);
}
我希望能够还处理IEnumerable<IEnumerable<string>>
和IEnumerable<IEnumerable<IEnumerable<string>>>
等,他们都以这种方式:
public static string MyJoin(this IEnumerable<IEnumerable<string>> strings)
{
return strings.Select(x => x.MyJoin()).MyJoin();
}
public static string MyJoin(this IEnumerable<IEnumerable<IEnumerable<string>>> strings)
{
return strings.Select(x => x.MyJoin()).MyJoin();
}
有什么方法可以在不对我可能要使用的所有可能级别进行硬编码的情况下,优雅地表达这一点?
部分受Stefan的答案启发,我已经找到了一个可行的解决方案,该解决方案无需使用泛型即可进行编译,并且(不幸的是)使用大多数运行时类型检查进行编译:
public static string MyJoin(this IEnumerable<string> strings)
{
return string.MyJoin(Environment.NewLine, strings);
}
public static string MyJoin(this IEnumerable<object> items)
{
if (items.All(x => x is string))
return items.Cast<string>().MyJoin();
if (items.All(x => x is IEnumerable<object>))
return items.Cast<IEnumerable<object>>().Select(x => x.MyJoin()).MyJoin();
throw new InvalidOperationException("The argument was not a nested enumerable of strings.");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句