【问题标题】:Use a switch statement to create file directories?使用 switch 语句创建文件目录?
【发布时间】:2015-08-07 04:29:36
【问题描述】:
我正在创建一个将安装在多个设备上的应用程序,并且我希望尽可能地自动设置每个设备的本地磁盘上的文件系统。除了使用几十个 if 语句之外,还有没有更简化的方法来使用 switch 语句来做到这一点?
if (System.IO.Directory.Exists(arctopithecusGalleryPath) == false)
{
System.IO.Directory.CreateDirectory(arctopithecusGalleryPath);
}
【问题讨论】:
标签:
c#
unity3d
io
switch-statement
【解决方案1】:
如何为此创建一个方法:
public void CreateIfNotExists(string path)
{
if (System.IO.Directory.Exists(path) == false)
{
System.IO.Directory.CreateDirectory(path);
}
}
然后像这样在你的代码中使用它:
CreateIfNotExists(arctopithecusGalleryPath);
或者,如果您有多个目录,您可以将它们添加到列表中并在 foreach 语句中调用此方法:
List<string> folders = new List<string>();
folders.Add("a folder to create");
// add more folders
foreach(var folder in folders)
{
CreateIfNotExists(folder);
}
【解决方案2】:
将变量存储在数组中并循环它们以避免多个 IF。
string[] arr1 = new string[] { arctopithecusGalleryPath, arctopithecusGalleryPath1, arctopithecusGalleryPath3 };
for (int i = 0; i < arr1.Length; i++)
{
if (System.IO.Directory.Exists(array[i]) == false){
System.IO.Directory.CreateDirectory(array[i]);
}