Try-catch在C#中创建新数组 - 在哪里初始化它?

Gli*_*kot -2 c# try-catch

如果我正在从配置文件中读取字符串,我将使用类似于下面的方法,以防正在读取的文件中出现字符串并产生异常.但是,如果我想对string []数组做同样的事情,我不能在try块之外"新建"因为大小未知.

我不能在try块本身新建它.应该如何处理?

string[] logContent; // can't new it up here as don't know the size

                try
                {
                    logContent = File.ReadAllLines(aLogFile);
                }
                catch
                {
                    throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");
                }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

您可以将其初始化为默认值:

string[] logContent = null; 
try
{
    logContent = File.ReadAllLines(aLogFile);
}
catch
{
    // Be careful with the error message here => there might be other reasons
    // that the ReadAllLines threw an exception
    throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");
}
Run Code Online (Sandbox Code Playgroud)