我想声明一个字符串数组,我使用的是这种方式:
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 块之外声明字符串数组吗?如果是这样怎么办?
字符串数组的名称不同,一个是
matchingActiveLogFiles
,另一个是matchingFiles
:
string[] matchingActiveLogFiles;
try
{
matchingActiveLogFiles = Directory.GetFiles(FilePath, FileNamePattern);
}
catch (Exception ex)
{
//log error
}
这将初始化您的数组:
string[] matchingActiveLogFiles = {};
try
{
matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
}
catch (Exception ex)
{
//logerror
}
但我想知道,你遇到了什么错误?即使使用未初始化的数组,上面的代码也应该可以工作。我还注意到您在第 1 行有“matchingActiveLogFiles”,在第 4 行有“matchingFiles”。也许这就是您的问题?
先初始化:
string[] matchingActiveLogFiles = new string[0];
问题是你的命名。您正在定义matchingActiveLogFiles,但分配matchingFiles。
您应该在需要该变量的范围内声明该变量。
虽然我通常不喜欢没有参数的方法,但这似乎是
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 ...
您不必知道项目的确切数量即可初始化数组,如
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
}