當我運行程式并為_moduleParent例外設定錯誤值時,會出現“物件參考未設定為物件的實體”。
我想回傳一個空字串。我該如何處理這個例外?
string sioModuleName = "";
string sioModuleDescription = String.Empty;
try
{
XDocument xDoc = new XDocument();
xDoc = XDocument.Load(_xmlPath);
//Root
var sioModule = xDoc.Element(_moduleName);
if(sioModule != null)
{
sioModuleName = sioModule.Element(_moduleParent).Value;//here is the problem
sioModuleDescription = sioModule.Element("SIO-DEFINITION").Value;
}
else
{
MessageBox.Show("Incorrect Module Name");
return;
}
}
uj5u.com熱心網友回復:
XContainer.Element(XName)XElement如果具有指定名稱的元素存在則回傳一個,否則它會回傳null。發生例外是因為您正在讀取Value空參考的屬性。所以你需要處理它。有兩種選擇:
使用內置的顯式轉換:
sioModuleName = (string)sioModule.Element(_moduleParent);
使用空條件運算子:
sioModuleName = sioModule.Element(_moduleParent)?.Value;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/454736.html
