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

Nir*_*ole 3 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
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*aev 5

简单的减量与--工作正常.

int? t = 50;
t--; // t now == 49
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

由于您无法使用refor out关键字标记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--;
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

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