C# 字符串数组的初始化
我想声明一个字符串数组,我使用的是这种方法:
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 块之外声明字符串数组吗?如果是的话怎么办?
I want to declare a string array, I was using this way of doing it:
string[] matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
which worked perfectly.
Now I want to enclose the Directory.GetFiles
call in a try
/catch
block, but I can't also have the declaration of the string array in there because then it won't be in the right scope to use it outside of the try
block. But if I try this:
string[] matchingActiveLogFiles;
try
{
matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
}
catch (Exception ex)
{
//log error
}
I have not initialized the string array so I have an error. So I am wondering what is best practise in this situation, should I declare the string array outside the try block? And if so how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
字符串数组的名称不同,一个是
matchingActiveLogFiles
,另一个是matchingFiles
:The name is different for the string arrays, one is
matchingActiveLogFiles
the other ismatchingFiles
:这将初始化您的数组:
但我想知道,您遇到了什么错误?
即使使用未初始化的数组,上面的代码也应该可以工作。
我还注意到您在第 1 行有“matchingActiveLogFiles”,在第 4 行有“matchingFiles”。也许这就是您的问题?
This will initialize your array:
But I'm wondering, what error are you getting?
Even with an uninitialized array, the above code should work.
I also noticed that you have "matchingActiveLogFiles" on line 1 and "matchingFiles" on line 4. Perhaps that's your problem?
问题是你的命名。您正在定义matchingActiveLogFiles,但分配matchingFiles。
The issue is your naming. You're defining matchingActiveLogFiles but assigning matchingFiles.
您应该在需要该变量的范围内声明该变量。
You should declare the variable in the scope in which that variable is needed.
您不必知道项目的确切数量即可初始化数组,例如
you do not have to know the exact number of Items in order to initialize an array like
首先初始化它:
Initialize it first:
虽然我通常不喜欢没有参数的方法,但这似乎是
Try
方法的一个很好的候选者:用法:
或者,只需将变量初始化为 null:
Though I generally dislike methods with out params, this seems like a good candidate for a
Try
method:Usage:
Or alternatively, just initialise your variable to null: