У меня есть код следующим образом внутри метода:Null ссылка на класс Cache вопрос
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 в моем случае?
EDIT: Я отправляю весь мой код:
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; }
}
Вы ссылались на эту ссылку: http://msdn.microsoft.com/en-us/library/18c1wd61(v=vs.100).aspx – Saravanan
, что вы храните в 'Cache [" Currency "] = someObject' line. я.e someobject имеет тип –
, кажется, что объект в 'Cache [" Currency "]' не имеет типа 'Dictionary>' –
ppetrov