简体   繁体   中英

Avoid changing the state of a variable when making use of 'Session' in C#

I want to save the result of a calculation (assigned to variable 'ans') for a second request. To do so, I use Session. Even though it worked in the first request, when I want to call the variable in a second request (else-Statement) the following error occurs :" Cannot apply indexing with [] to an expression of type 'object' "

Does the state of the variable change through saving it to /accessing it from Session?

The format of 'ans' and 'ansTemp' for the second request is both times tuple of 5 items.

private Dictionary<string,int> DoCalculation(CalculatorModel model)
{
        var ansTemp = Session["ANS"];
        Dictionary<string, int> calculatedValues = new Dictionary<string, int>();
        if (ansTemp == null)
        {
            if (model != null)
            {
                Class1 clsOne = new Class1(pathToLib, pathToPyFile);
                try
                {
                    var ans = clsOne.CallFunction("first_chart", rootPythonDir, model.age);

                    //Session.Add("ANS", ans);
                    Session["ANS"] = ans;
                    var assetAllocationCategory = ans[1];

                 }
                 catch (Exception ex) { }
             }
         }
         else
         {
             var ans = ansTemp;
             var assetAllocationCategory = ans[1];
         }
}

在访问Session [“ ANS”]时将ansTemp定义为动态变量而不是var可以解决此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM