dpp*_*dpp 1 c# asp.net-mvc null-coalescing-operator
我正在尝试在我的页面上创建分页.用户可以选择每页显示的项目数,然后首选大小将保存为cookie.但是当我尝试在querystring参数和cookie之间进行选择时,发生了错误:
public ActionResult Index(string keyword, int? page, int? size)
{
keyword = keyword ?? "";
page = page ?? 1;
//Operator "??" cannot be applied to operands of type "int" and "int"
size = size ?? Convert.ToInt32(Request.Cookies.Get("StoriesPageSize").Value) ?? 10;
Run Code Online (Sandbox Code Playgroud)
是什么导致了这个错误?怎么解决?
Convert.ToInt32只返回int,而不是int?- 所以表达式的类型:
size ?? Convert.ToInt32(...)
Run Code Online (Sandbox Code Playgroud)
是类型的int.您不能使用非可空值类型作为空合并运算符表达式的第一个操作数 - 它不可能为null,因此永远不可能使用第二个操作数(在本例中为10).
如果你试图尝试使用StoriesPageSizecookie,但你不知道它是否存在,你可以使用:
public ActionResult Index(string keyword, int? page, int? size)
{
keyword = keyword ?? "";
page = page ?? 1;
size = size ?? GetSizeFromCookie() ?? 10;
}
private int? GetSizeFromCookie()
{
string cookieValue = Request.Cookies.Get("StoriesPageSize").Value;
if (cookieValue == null)
{
return null;
}
int size;
if (int.TryParse(cookieValue, CultureInfo.InvariantCulture, out size))
{
return size;
}
// Couldn't parse...
return null;
}
Run Code Online (Sandbox Code Playgroud)
正如评论中所提到的,您可以编写一个扩展方法来使其更普遍可用:
public static int? GetInt32OrNull(this CookieCollection cookies, string name)
{
if (cookies == null)
{
throw ArgumentNullException("cookies");
}
if (name == null)
{
throw ArgumentNullException("name");
}
string cookieValue = cookies.Get(name).Value;
if (cookieValue == null)
{
return null;
}
int size;
if (int.TryParse(cookieValue, CultureInfo.InvariantCulture, out size))
{
return size;
}
// Couldn't parse...
return null;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已经更改了代码以使用不变文化 - 在不变文化中传播cookie中的信息是有意义的,因为它并不真正意味着用户可见或文化敏感.您应该确保使用不变文化保存 cookie.
无论如何,使用扩展方法(在静态非通用顶级类中),您可以使用:
size = size ?? Request.Cookies.GetInt32OrNull("StoriesPageSize") ?? 10;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1044 次 |
| 最近记录: |