C#String数组的初始化

时间:2012-01-04 17:29:18

标签: c# arrays string

我想声明一个字符串数组,我正在使用这种方式

string[] matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);

完美的工作,但现在我想在一个try / catch块中包含Directory.GetFiles调用,但我不能在那里有字符串数组的声明,因为它不会在正确的范围内使用它在try块之外。但如果我试试这个:

string[] matchingActiveLogFiles;
            try
            {
                matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
            }
            catch (Exception ex)
            {
                //logerror
            }

我没有初始化字符串数组,所以我有一个错误。所以我想知道在这种情况下最佳做法是什么,我应该在try块之外声明字符串数组吗?如果是这样的话?

7 个答案:

答案 0 :(得分:3)

字符串数组的名称不同,一个是matchingActiveLogFiles,另一个是matchingFiles string[] matchingActiveLogFiles; try { matchingActiveLogFiles = Directory.GetFiles(FilePath, FileNamePattern); } catch (Exception ex) { //logerror }

{{1}}

答案 1 :(得分:1)

这会初始化你的数组:

string[] matchingActiveLogFiles = {};
            try
            {
                matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
            }
            catch (Exception ex)
            {
                //logerror
            }

但我想知道,你得到了什么错误?即使使用未初始化的数组,上述代码也应该有效。我还注意到你在第1行有“matchingActiveLogFiles”,在第4行有“matchingFiles”。也许这是你的问题?

答案 2 :(得分:1)

首先初始化它:

 string[] matchingActiveLogFiles = new string[0];

答案 3 :(得分:0)

虽然我一般不喜欢没有params的方法,但这似乎是Try方法的一个很好的候选者:

bool TryGetMatchingLogFiles(out string[] matchingFiles )
{
  matchingFiles = null;
  try
  {
     matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
     return true;
  }
  catch (Exception ex)
  {
     //logerror
     return false;
  }
}

用法:

string[] matchingActiveLogFiles;
if (TryGetMatchingLogFiles(out matchingActiveLogFiles))
{
  // Use matchingActiveLogFiles here
}

或者,只需将变量初始化为null:

string[] matchingActiveLogFiles = null;
try ...

答案 4 :(得分:0)

问题在于你的命名。您正在定义matchingActiveLogFiles但指定匹配文件。

答案 5 :(得分:0)

您应该在需要该变量的范围内声明变量。

  • 如果您只需要try块中的变量,请将其放在那里!
  • 如果您需要在try块之外,如果您的代码无法获取文件内容,您希望该值是什么?将其设置为出错时。

答案 6 :(得分:0)

为了初始化数组,你不必知道确切的项目数,如

 string[] matchingActiveLogFiles = {}; 
this is what is called a dynamic array it's totally functional and I've had ZERO issues with declaring arrays this way.. 

List<string> matchingFiles= new List<string>();
try
 {
    matchingFiles.Add(Directory.GetFiles(FilePath, FileNamePattern));
    matchingActiveLogFiles = matchingFiles.ToArray(); 
 }
 catch (Exception ex)
 {
    //logerror
 }