如何在mvc4 c#中递减可空值int by1
本文关键字:空值 int by1 mvc4 | 更新日期: 2023-09-27 18:05:13
我有一个操作方法如下:
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
}
}
我如上所述尝试过,但它没有减量。基本上它是可空的;有什么方法可以解决这个问题吗?谢谢你
使用--
进行简单减量就可以了。
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?
的副本传递给方法,而不是引用。
因为你不能为ASP标记参数。NET MVC4控制器方法与ref
或out
关键字(它会导致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--;
}
}
在这种情况下,您将使用一个对象,而不是对象的多个副本。
如果你从视图调用方法,ASP.NET
默认绑定器将自动创建一个PassItem
的实例,并设置它的属性与所需的值
可空类型被视为结构体(https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx) -因此作为参数按值传递。你是在递减堆栈上的值,如果你想改变实际值,你需要传递page作为ref或out参数
public PartialViewResult batchSave(int? clientId, string uploadidList, int? currentFilter, ref int? page)
{}
减少了按值传递的结构体的副本。使用'ref'
static void foo(ref int? val)
{
if (val != null)
{
--val;
}
}
static void Main(string[] args)
{
int? val = 5;
foo(ref val);
}
最好使用预操作,因为后操作返回操作前值的副本。一般来说,这不是最优的。