Path.Combine如何与超过2个参数一起使用? [英] How can Path.Combine be used with more than 2 arguments?
问题描述
我很惊讶没有可以采用字符串数组的重载。无论如何,避免嵌入对Path.Combine的调用的最佳方法是什么?
I'm surprised there's not an overload that can take a string array. Anyway, what is the best way to avoid nesting calls to Path.Combine?
pathValue = Path.Combine(path1, Path.Combine(path2, Path.Combine(path3, path4)))
这似乎效率低,因为它导致创建4个新字符串只是为了得到1.
This seems inefficient since it results in 4 new strings being created just to get 1.
推荐答案
事情的效率方面不是问题IMO - 它是可用性事情的一面。我个人认为应该有一个重载:
The efficiency side of things isn't the problem IMO - it's the usability side of things. Personally I think there ought to be an overload of:
Combine(string first, string second, string third, params string[] others)
你需要至少有三个以防止它与现有的双参数版本发生冲突如果你只是写 Path.Combine(foo,bar)
但它肯定有助于使代码更清晰。为什么不在连接上打开功能请求?
You need to have at least three to prevent it from clashing with the existing two-parameter version if you just write Path.Combine("foo", "bar")
but it would certainly help to make code clearer. Why not open a feature request on Connect?
当然,你可以自己实现这个(在另一个类中,参数的数量并不重要):
Of course, you can implement this yourself (and in another class the number of parameters doesn't matter so much):
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;
}
这篇关于Path.Combine如何与超过2个参数一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!