我有下面的C#代码,我不知道它为什么不工作(我得到了一个NullReferenceException错误)。如果我将Recipe定义为new List(),一切都会正常工作。
foreach (XElement element in document.Descendants("vegetables"))
{
VegetablesList = (
from vegetables in element.Elements()
select new FoodItem()
{
Name = (vegetables.Element("name") == null) ? null : vegetables.Element("name").Value.ToString(),
Bcg = (vegetables.Element("bcg") == null) ? null : vegetables.Element("bcg").Value.ToString(),
Info = (vegetables.Element("info") == null) ? null : vegetables.Element("info").Value.ToString(),
Recipes = (
from recipes in element.Element("recipes").Elements()
select new Recipe()
{
Name = (recipes.Element("name") == null) ? null : recipes.Element("name").Value.ToString(),
Text = (recipes.Element("text") == null) ? null : recipes.Element("text").Value.ToString()
}
).ToList()
}
).ToList();
VegetablesListBox.ItemsSource = VegetablesList;
}
谢谢你的帮助!