如何在mvc4 c#中减少nullable int by1?

时间:2016-09-02 08:33:14

标签: c# asp.net-mvc-4

我有一个动作方法如下:

public PartialViewResult batchSave(int? clientId, string uploadidList, int? currentFilter, int? page)
{
    if(page!=null)
    {
        page--;// This is also not working
        page=page-1; //Does not works
    } 
}

我尝试了如上,但它并没有减少。基本上它是可以为空的;那有什么方法可以解决这个问题吗?谢谢

3 个答案:

答案 0 :(得分:5)

--的简单递减工作正常。

int? t = 50;
t--; // t now == 49

我猜,问题在于比较此方法后的结果:

public void Dec(int? t) 
{
    if (t != null) 
    {
        t--; //if initial t == 50, then after this t == 49.
    }
}
...
int? t = 50;
Dec(t); // but here t is still == 50

看看@PaulF答案,它包含解释,为什么int?的副本传递给方法而不是参考。

由于您无法使用refout关键字标记ASP.NET MVC4控制器方法的参数(在调用方法时会导致ArgumentException),我建议您使用具有多个属性的单个类。

因此,在递减时,您将处理类的属性,它通过引用传递,而不是int?变量的副本(AFAIK,这是一个很好的做法)。

在您的情况下,您的代码可以修改如下:

public class PassItem 
{
   public int? clientId { get; set; }
   public string uploadidList { get; set; }
   public int? currentFilter { get; set; }
   public int? page { get; set; }
}

public PartialViewResult batchSave(PassItem passItem)
{
    if(passItem.page != null)
    {
        passItem.page--;
    } 
}

在这种情况下,您将使用一个对象,而不是多个对象副本。

如果您使用View中的方法调用,ASP.NET默认活页夹将自动创建PassItem的实例,并使用所需的值设置其属性。

答案 1 :(得分:1)

Nullable类型被视为结构(https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx) - 因此通过值作为参数传递。如果要更改将页面作为ref或out参数传递所需的实际值,则递减堆栈上的值

public PartialViewResult batchSave(int? clientId, string uploadidList, int? currentFilter, ref int? page)

{     }

答案 2 :(得分:0)

减少按值传递的结构的副本。使用'ref'

static void foo(ref int? val)
{
    if (val != null)
    {
        --val;
    }
}

static void Main(string[] args)
{
    int? val = 5;
    foo(ref val);
}

使用预操作也更好,因为后操作会返回值的副本,该副本在操作之前。这通常不是最佳的。操作前不使用副本。