Path.Combine如何与两个以上的参数一起使用?

Rob*_*ers 22 .net string io concatenation path

我很惊讶没有可以采用字符串数组的重载.无论如何,避免嵌入对Path.Combine的调用的最佳方法是什么?

pathValue = Path.Combine(path1, Path.Combine(path2, Path.Combine(path3, path4)))
Run Code Online (Sandbox Code Playgroud)

这似乎效率低下,因为它会导致创建四个新字符串以获得一个.

Mar*_*eck 27

如果你已经有一个数组或IEnumerable <T>那么你可以在一行中完成这个...

// I'm assuming that you've got an array or IEnumerable<T> from somewhere
var paths = new string[] { path1, path2, path3, path4, path5, path6 };

string result = paths.Aggregate(Path.Combine);
Run Code Online (Sandbox Code Playgroud)

如果没有,那么将自己的扩展方法写入字符串...

public static class PathExtension
{
    public static string CombinePathWith(this string path1, string path2)
    {
        return Path.Combine(path1, path2);
    }
}
Run Code Online (Sandbox Code Playgroud)

......这会让你把这些链接起来......

string result = path1.CombinePathWith(path2)
                     .CombinePathWith(path3)
                     .CombinePathWith(path4)
                     .CombinePathWith(path5)
                     .CombinePathWith(path6);
Run Code Online (Sandbox Code Playgroud)

  • 很酷,我不知道Enumerable.Aggregate! (4认同)

Jon*_*eet 23

事物的效率方面不是IMO的问题 - 它是事物的可用性方面.我个人认为应该有一个超载:

Combine(string first, string second, string third, params string[] others)
Run Code Online (Sandbox Code Playgroud)

你需要至少有三个以防止它与现有的双参数版本冲突,如果你只是写,Path.Combine("foo", "bar")但它肯定有助于使代码更清晰.为什么不在Connect上打开功能请求?

当然,你可以自己实现它(在另一个类中,参数的数量并不重要):

public static string CombinePaths(string first, params string[] others)
{
    // Put error checking in here :)
    string path = first;
    foreach (string section in others)
    {
        path = Path.Combine(path, section);
    }
    return path;
}
Run Code Online (Sandbox Code Playgroud)

  • OP的愿望已被授予.在.net 4 Beta2中添加了对Path.Combine(params)的支持 - http://blogs.msdn.com/bclteam/archive/2009/10/21/what-s-new-in-the-bcl-in -net-4-β-2-贾斯汀-VAN-patten.aspx (6认同)