C#字符串数组的初始化

问题描述 投票:0回答:7

我想声明一个字符串数组,我使用的是这种方式:

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

效果非常好。

现在我想将

Directory.GetFiles
调用包含在
try
/
catch
块中,但我也不能在其中声明字符串数组,因为那样它就不会在正确的范围内使用它位于
try
块之外。但如果我尝试这个:

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

我还没有初始化字符串数组,所以出现错误。所以我想知道在这种情况下的最佳实践是什么,我应该在 try 块之外声明字符串数组吗?如果是这样怎么办?

c# arrays string variable-declaration variable-initialization
7个回答
4
投票

字符串数组的名称不同,一个是

matchingActiveLogFiles
,另一个是
matchingFiles

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

1
投票

这将初始化您的数组:

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

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


1
投票

先初始化:

 string[] matchingActiveLogFiles = new string[0];

0
投票

问题是你的命名。您正在定义matchingActiveLogFiles,但分配matchingFiles。


0
投票

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

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

0
投票

虽然我通常不喜欢没有参数的方法,但这似乎是

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 ...

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
 }  
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.