从 C# 中的组件构建目录字符串
如果我有很多目录名称作为文字字符串或包含在变量中,那么将它们组合起来形成完整路径的最简单方法是什么?
我知道
Path.Combinebut this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.
例如:
string folder1 = "foo"; string folder2 = "bar"; CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
有什么想法吗? C# 是否支持方法中的无限参数?
If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?
I know of
Path.Combine
but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.
e.g:
string folder1 = "foo"; string folder2 = "bar"; CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
Any ideas?
Does C# support unlimited args in methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,看看 params 关键字。 可以轻松编写一个仅调用 Path.Combine 适当次数的函数,如下所示(未经测试):
Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):
LINQ 再次来救援。 Aggregate 扩展函数可用于完成你想要的。 考虑这个例子:
LINQ to the rescue again. The Aggregate extension function can be used to accomplish what you want. Consider this example:
与 Directory 上的静态方法相比,我更喜欢使用 DirectoryInfo,因为我认为这是更好的 OO 设计。 这是一个使用 DirectoryInfo + 扩展方法的解决方案,我认为使用起来非常好:
我不喜欢修改
self
的事实,但对于这个简短的方法,我认为它比创建一个新变量。不过,调用站点弥补了这一点:
添加一种获取 FileInfo 的方法留作练习(对于另一个 SO 问题!)。
I prefer to use DirectoryInfo vs. the static methods on Directory, because I think it's better OO design. Here's a solution with DirectoryInfo + extension methods, that I think is quite nice to use:
I don't love the fact that I'm modifying
self
, but for this short method, I think it's cleaner than making a new variable.The call site makes up for it, though:
Adding a way to get a FileInfo is left as an exercise (for another SO question!).
试试这个:
参数使您可以附加无限数量的字符串。
Path.Combine 的作用是确保输入的字符串不以斜杠开头或结尾,并检查是否有任何无效字符。
Try this one:
The params makes it so that you can append an infinite amount of strings.
Path.Combine does is to make sure that the inputted strings does not begin with or ends with slashes and checks for any invalid characters.