2

我正在尝试使用String.Split方法在每行拆分我的字符串列表,但是下面的方法和正则表达式方法都不起作用。相反,他们返回了以下结果{0} 0. System.String[],而不是实际的字符串数组。请帮助查找以下代码中的错误:

    string m_settings_temp;
    string[] m_settings;
    public void ShowSettingsGui() {
       var dialog = new OpenFileDialog { Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*" };
       if (dialog.ShowDialog() != DialogResult.OK) return;
       m_settings_temp = File.ReadAllText(dialog.FileName);
       m_settings = m_settings_temp.Split(new [] { '\r', '\n' });
       //This regex method failed as well:  
       //m_settings = Regex.Split(m_settings_temp,"\r\n|\r|\n");
    }

    //The method below is to evaluate the output
    protected override void SolveInstance(IGH_DataAccess DA)
                    {
                        if (m_settings == null)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "You must declare some valid settings");
                            return;
                        }
                        DA.SetData(0, m_settings);
                    }

提前致谢!

4

3 回答 3

7

ReadAllLines像这样使用

m_settings = File.ReadAllLines(dialog.FileName);

这将为您string[]提供所选文件中每一行的元素。如果在运行此代码后m_settings没有元素,则您选择的文件为空。


如果我想查询m_settings控制台应用程序中的内容,我可能会做类似的事情。

for (var i = 0; i < m_settings.Length; i ++)
{
    Console.WriteLine(m_settings[i]);
}

这将输出数组的内容,一次一个元素。如果我使用ToStringfor am 数组的实现,像这样,

Console.WriterLine(m_settings);

我会得到数组类型和它包含的元素数量的字符串表示形式。


我怀疑在你的情况下你想做类似的事情

protected override void SolveInstance(IGH_DataAccess DA)
{
     if (m_settings == null || m_settings.Length == 0)
     {
         AddRuntimeMessage(
              GH_RuntimeMessageLevel.Warning,
              "You must declare some valid settings");

         return;
     }

     for (var i = 0; i < m_settings.Length; i ++)
     {
         DA.SetData(i, m_settings[i]);
     }
}
于 2012-08-13T10:28:48.970 回答
1
m_settings = m_settings_temp
    .Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
于 2012-08-13T10:28:32.127 回答
1
string m_settings_temp;
string[] m_settings;
public void ShowSettingsGui()
{
    var dialog = new OpenFileDialog { Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*" };
    if (dialog.ShowDialog() != DialogResult.OK) return;

    m_settings_temp = File.ReadAllText(dialog.FileName);
    m_settings = m_settings_temp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
于 2012-08-13T10:31:12.967 回答