メソッド内に次のようなコードがあります。
var currency = new Dictionary<string, List<Currency>>();
if (Cache["Currency"] == null)
{
//here I fill currency with data and then set it to Cache.
Cache["Currency"] = currency ;
}
else
{
var currency = Cache["Currency"] as Dictionary<string, List<Currency>>;
//here I am getting null reference exception:
foreach (var item in currency)
}
アプリケーションから Cache クラスを直接使用するべきではないことを読みましたが、私の場合の Cache クラスの適切な使用法は何ですか?
編集:すべてのコードを投稿しています:
protected void DisplayCurrency()
{
Dictionary<string, List<Currency>> currList = new Dictionary<string, List<Currency>>();
if (Cache["Currency"] == null)
{
var xmlDoc = XElement.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
if (xmlDoc != null)
{
var queryXML = from xml in xmlDoc.Elements("Currency")
where (string)xml.Attribute("Kod") == "USD" || (string)xml.Attribute("Kod") == "EUR"
select xml;
if (queryXML != null)
{
//fill Dictionary with data
foreach (var item in queryXML)
{
currList.Add(item.Attribute("Kod").Value, new List<Currency>
{
new Currency
{
ForexBuying = item.Element("ForexBuying").Value,
ForexSelling = item.Element("ForexSelling").Value,
BanknoteBuying = item.Element("BanknoteBuying").Value,
BanknoteSelling= item.Element("BanknoteSelling").Value
}
});
}
//Cache["Currency"] = currList;
HttpContext.Current.Cache["Currency"] = currList;
//read data from Dictionary instance
foreach (var item in currList)
{
switch (item.Key)
{
case "USD":
litUSDtxt.Text = item.Key;
foreach (var i in item.Value)
{
litUSD.Text = i.BanknoteSelling;
}
break;
case "EUR":
litEURtxt.Text = item.Key;
foreach (var i in item.Value)
{
litEUR.Text = i.BanknoteSelling;
}
break;
}
}
}
}
// Cache.Insert("Currency", currList, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
}
else
{
var currency = Cache["Currency"] as Dictionary<string, List<Currency>>;
foreach (var item in currency)
{
switch (item.Key)
{
case "USD":
litUSDtxt.Text = item.Key;
foreach (var i in item.Value)
{
litUSD.Text = i.BanknoteSelling;
}
break;
case "EUR":
litEURtxt.Text = item.Key;
foreach (var i in item.Value)
{
litEUR.Text = i.BanknoteSelling;
}
break;
}
}
}
}
class Currency
{
public string ForexBuying { get; set; }
public string ForexSelling { get; set; }
public string BanknoteBuying { get; set; }
public string BanknoteSelling { get; set; }
}