對於.net 3.5只是咬緊牙關它是最乾淨的外觀解決方案。
public struct Wave{
public X time;
public Y enable;
}
public static Wave GetWaveAnimation()
{
try
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select new Wave
{
time = element.Attribute("TIMING").Value,
enable = element.Attribute("ENABLED").Value
}).FirstOrDefault();
}
catch { return null; }
}
對於.NET 4.0您可以使用動態關鍵字(但因爲匿名類型是內部的,你不能從你的程序集或朋友組件的外部調用此方法。)
public static dynamic GetWaveAnimation()
{
try
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select new
{
time = element.Attribute("TIMING").Value,
enable = element.Attribute("ENABLED").Value
}).FirstOrDefault();
}
catch { return null; }
}
OR你的元組選
public static Tuple<X,Y> GetWaveAnimation()
{
try
{
return (from element in configurations.Elements("Animation")
where element.Attribute("NAME").Value == "Wave"
select Tuple.Create(
element.Attribute("TIMING").Value,
element.Attribute("ENABLED").Value
)
}).FirstOrDefault();
}
catch { return null; }
}
什麼是錯誤信息?你知道你不能使用'var'讓編譯器爲你推斷返回類型,但是返回'object'應該編譯。 – 2011-03-10 10:19:59
Noooooo ......刪除那個catch塊。你爲什麼認爲你需要它? – 2011-03-10 10:20:16
哦,你是對的,一開始我還沒有「FirstOrDefault()」,我不確定如果函數拋出一個異常,如果它找不到XElement – jwillmer 2011-03-10 10:35:09