【问题标题】:c# internal string array methodc#内部字符串数组方法
【发布时间】:2016-02-25 08:08:33
【问题描述】:

我想要求用户使用方法指定文件夹路径并将其保存在数组中,然后允许以后使用该数组。我遇到的问题是定义返回类型。我应该如何构建方法?

internal void selectFolderTxt(out string [] files)
{
    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       string[] files = Directory.GetFiles(fbd.SelectedPath, "*.txt", SearchOption.AllDirectories);//change this to specify file type
    }
    else
    {
        // prevents crash
    }
}

附:我才刚刚开始学习使用方法。

【问题讨论】:

  • 你需要的返回类型是什么?只需在这里替换 ==> 内部 [-->void

标签: c# arrays methods


【解决方案1】:

我稍微改变一下解决方案。

单个存在点很重要

Why should a function have only one exit-point?

internal string[] selectFolderTxt() {
    string[] resultFiles = null;

    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       resultFiles = Directory.GetFiles(fbd.SelectedPath, "*.txt", SearchOption.AllDirectories);//change this to specify file type
    }

    return resultFiles 
}

【讨论】:

  • 别忘了分号。
【解决方案2】:
internal string[] selectFolderTxt() {

    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       return Directory.GetFiles(fbd.SelectedPath, "*.txt", SearchOption.AllDirectories);//change this to specify file type
    }
    else
    {
    // prevents crash
       return null;
    }
}

用法:

string[] files = selectFolderTxt();
if (files != null)
{
   // use files
}
else
{
   // the user cancelled dialog
}

【讨论】:

  • 感谢您的一百万次,这对您有很大帮助。我将来会重新考虑事情。这样可以实现更多功能。
  • 这是解决方案,但此方法没有 Single Exit Point 。你可以看看stackoverflow.com/questions/4838828/…
【解决方案3】:

你应该使用 boolean (internal boolean selectFolderTxt(out string [] files) )。如果 OK,则为 true,如果错误或用户取消则为 false,否则为 false。

【讨论】:

    猜你喜欢
    • 2019-05-25
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多