Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 会话像原语类型一样传递?_C#_.net_Asp.net Mvc_Pass By Reference_Pass By Value - Fatal编程技术网

C# 会话像原语类型一样传递?

C# 会话像原语类型一样传递?,c#,.net,asp.net-mvc,pass-by-reference,pass-by-value,C#,.net,Asp.net Mvc,Pass By Reference,Pass By Value,我有一个MVC Core Dotnet应用程序,基本上我希望加载会话数据的视图,但也希望在页面加载后删除会话。我的代码可以工作,但我不明白为什么 public IActionResult Charge(string stripeEmail, string stripeToken, int totalPrice){ //some stripe code that went here... var cart = HttpContext.Session.GetCart();

我有一个MVC Core Dotnet应用程序,基本上我希望加载会话数据的视图,但也希望在页面加载后删除会话。我的代码可以工作,但我不明白为什么

public IActionResult Charge(string stripeEmail, string stripeToken, int totalPrice){
    //some stripe code that went here...

    var cart = HttpContext.Session.GetCart();
    ClearSession();
    return View(cart);
}

protected void ClearSession(){
    //creates a new instance if cart doesnt exist otherwise returns it
    var cart = HttpContext.Session.GetCart();

    //clears the items from the collection using .Clear() ...
    cart.RemoveAll();
    HttpContext.Session.SetCart(cart);
}
当代码被放入这样的新方法中时,它就会工作。。但是如果我用同样的方法,它就不起作用了。我很惊讶将它放在一个新的方法中,因为它违背了我对传递值如何处理对象类型的理解。。(将传递对象的位置)。当我在新方法中清除项目列表时,它的行为就像对象的副本一样


为什么这段代码有效?

当您执行
var cart=HttpContext.Session.GetCart()时
Charge
方法中,它创建会话中任何内容的本地副本,并将其传递给视图。在方法
ClearSession
中,创建并修改另一个本地副本,并将其保存回会话。这就是它的工作原理。要获得所需的行为,您需要创建一个空集合,并在执行
var cart=HttpContext.session.GetCart()之后将其保存到会话
以清除会话。