C# 缓存类问题上的空引用

C# 缓存类问题上的空引用,c#,caching,nullreferenceexception,C#,Caching,Nullreferenceexception,我在方法内部有如下代码: 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["

我在方法内部有如下代码:

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)
}
var currency=newdictionary();
如果(缓存[“货币”]==null)
{
//在这里,我用数据填充货币,然后将其设置为缓存。
缓存[“货币”]=货币;
}
其他的
{
var currency=Cache[“currency”]作为字典;
//这里我得到了空引用异常:
foreach(以货币表示的var项目)
}
我已经读到缓存类不应该直接从我的应用程序中使用, 但在我的例子中,缓存类的正确用法是什么

编辑: 我正在发布我的所有代码:

 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; }
}
受保护的void DisplayCurrency()
{
字典列表=新字典();
如果(缓存[“货币”]==null)
{
var xmlDoc=XElement.Load(“http://www.tcmb.gov.tr/kurlar/today.xml");
如果(xmlDoc!=null)
{
var queryXML=来自xmlDoc.Elements(“货币”)中的xml
其中(字符串)xml.Attribute(“Kod”)=“USD”| |(字符串)xml.Attribute(“Kod”)=“EUR”
选择xml;
if(queryXML!=null)
{
//用数据填充字典
foreach(queryXML中的变量项)
{
currList.Add(item.Attribute(“Kod”).Value,新列表
{
新货币
{     
ForexBuying=item.Element(“ForexBuying”).Value,
ForexSelling=item.Element(“ForexSelling”).Value,
BanknoteBuying=item.Element(“BanknoteBuying”).Value,
BanknoteSelling=项目.元素(“BanknoteSelling”).值
}
});
}
//缓存[“货币”]=货币列表;
HttpContext.Current.Cache[“Currency”]=currList;
//从字典实例读取数据
foreach(currList中的var项)
{
开关(项目.钥匙)
{
“美元”一案:
litUSDtxt.Text=item.Key;
foreach(项目值中的var i)
{
litUSD.Text=i.纸币销售;
}
打破
“欧元”案:
Text=item.Key;
foreach(项目值中的var i)
{
litEUR.Text=i.纸币销售;
}
打破
}
}
}
}
//Insert(“Currency”、currList、null、DateTime.Now.AddDays(1)、TimeSpan.Zero);
}
其他的
{
var currency=Cache[“currency”]作为字典;
foreach(以货币表示的var项目)
{
开关(项目.钥匙)
{
“美元”一案:
litUSDtxt.Text=item.Key;
foreach(项目值中的var i)
{
litUSD.Text=i.纸币销售;
}
打破
“欧元”案:
Text=item.Key;
foreach(项目值中的var i)
{
litEUR.Text=i.纸币销售;
}
打破
}
}
}
}
类别货币
{
公共字符串ForexBuying{get;set;}
公共字符串ForexSelling{get;set;}
公共字符串钞票购买{get;set;}
公开字符串钞票出售{get;set;}
}

我认为您将其设置为错误的变量,是不是:

Cache["Currency"] = currency;
而不是:

Cache["Currency"] = someObject;
或者,如果您真的想使用
someObject
的话,请确保它是
Dictionary
类型,否则
将返回
null

编辑

确保使用的是
HttpContext.Cache
,这是一个常见问题:

HttpContext.Cache["Currency"] = currency;
首先有几点:

  • 不要每次都初始化
    货币
    。当缓存已经包含实例时,这是浪费时间
  • 永远不要尝试检查缓存中的内容,然后分两个不同的步骤检索它。在这些步骤之间,缓存可能已被另一个进程清除,从而创建
    NullReferenceException
  • 在问题的第一次编辑中,您将一些其他对象放入缓存中。在其他位置检查您的软件。如果代码
    Cache[“Currency”]
    中的任何位置填充了另一种类型的对象,则
    as
    操作将始终返回
    null
  • 您的代码必须如下所示:

    var currency = Cache["Currency"] as Dictionary<string, List<Currency>>;
    if (currency == null)
    {
        currency = new Dictionary<string, List<Currency>>();
        // At this point, initialize currency, fill it with data from your XML file, or whatever.
        Cache["Currency"] = currency;
    }
    // At this point, currency is loaded from cache or recreated. Now you can use it to fill your controls, variables, etc.
    
    var currency=Cache[“currency”]作为字典;
    如果(货币==null)
    {
    货币=新字典();
    //在这一点上,初始化货币,用XML文件中的数据填充货币,或者其他任何东西。
    缓存[“货币”]=货币;
    }
    //此时,将从缓存加载或重新创建货币。现在您可以使用它来填充控件、变量等。
    
    或者。。。要修改整个代码,请执行以下操作:

    protected void DisplayCurrency()
    {
        var currency = Cache["Currency"] as Dictionary<string, List<Currency>>;
    
        if (currency == null)
        {
            currency = new Dictionary<string,List<Currency>>();
            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)
                    {
                        currency.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"] = 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;
            }
        }
    }
    
    受保护的void DisplayCurrency()
    {
    var currency=Cache[“currency”]作为字典;
    如果(货币==null)
    {
    货币=新字典();
    var xmlDoc=XElement.Load(“http://www.tcmb.gov.tr/kurlar/today.xml");
    如果(xmlDoc!=null)
    {
    var queryXML=来自xmlDoc.Elements(“货币”)中的xml
    其中(字符串)xml.Attribute(“Kod”)=“USD”| |(字符串)xml.Attribute(“Kod”)=“EUR”
    选择xml;
    if(queryXML!=null)
    {
    //用数据填充字典
    foreach(queryXML中的变量项)
    {
    
    var currency = Cache["Currency"] as Dictionary<string, List<Currency>>;
    if (currency == null)
    {
        currency = new Dictionary<string, List<Currency>>();
        // At this point, initialize currency, fill it with data from your XML file, or whatever.
        Cache["Currency"] = currency;
    }
    // At this point, currency is loaded from cache or recreated. Now you can use it to fill your controls, variables, etc.
    
    protected void DisplayCurrency()
    {
        var currency = Cache["Currency"] as Dictionary<string, List<Currency>>;
    
        if (currency == null)
        {
            currency = new Dictionary<string,List<Currency>>();
            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)
                    {
                        currency.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"] = 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;
            }
        }
    }
    
    else
    {
      currrency = Cache["Currency"] ;
     //here I am getting null reference exception:
     foreach (var item in currency)
    }