使用此功能:
public void GetOutlineDateAndMediaClassification(string talksdatabase, int talknumber, out DateTime date, out bool hasMedia)
{
date = new DateTime(1900, 1, 1);
hasMedia = false;
try
{
XDocument doc = XDocument.Load(talksdatabase);
var ptInfo = doc
.Descendants("PublicTalk")
.Where(p => p.Attribute("Number").Value == talknumber.ToString()).First();
if (ptInfo != null)
{
date = DateTime.Parse(ptInfo.Attribute("IssueDate").Value).Date;
hasMedia = Convert.ToBoolean(ptInfo.Attribute("Media").Value);
}
}
catch (Exception ex)
{
SimpleLog.Log(ex);
}
}
它有两个
out
参数。我希望将 default 值分配到 try
块的内部。但系统标记它们尚未初始化。
所以我将它们移到了函数的顶部。但是
DateTime
构造函数可能会出现异常,这就是为什么我想在 try
块中声明它。
解决这个难题的正确方法是什么?
如果输出参数设置在
try
块内,则可能会出现代码在设置输出参数之前抛出异常的情况。在这种情况下,代码将继续在 catch 块中执行。如果您也将它们设置在那里,或者抛出异常,那就没问题了。但由于您不这样做,您将从函数返回而无需设置输出参数。这是不允许的。
为了更清楚,请参阅我添加到您的代码中的注释:
public void GetOutlineDateAndMediaClassification(string talksdatabase, int talknumber, out DateTime date, out bool hasMedia)
{
try
{
XDocument doc = XDocument.Load(talksdatabase); // (1) Assume Document.Load(talksdatabase) throws an exception. Note that you have not set date or hasMedia yet.
var ptInfo = doc
.Descendants("PublicTalk")
.Where(p => p.Attribute("Number").Value == talknumber.ToString()).First();
date = new DateTime(1900, 1, 1);
hasMedia = false;
if (ptInfo != null)
{
date = DateTime.Parse(ptInfo.Attribute("IssueDate").Value).Date;
hasMedia = Convert.ToBoolean(ptInfo.Attribute("Media").Value);
}
}
catch (Exception ex)
{
// (2) Your code will continue here after (1) without executing the rest of the try-block. date and hasMedia still have not been set.
SimpleLog.Log(ex);
}
// (3) There is no more code to execute but date and hasMedia are not set. This is invalid.
}