c# - 哇,什么是 TryParse

标签 c# asp.net asp.net-mvc webforms

我有一个包含特定整数值的 session ,这些整数值用给定的控件进行索引。通常,以下内容会工作得很好:

int value;
int.TryParse(Session["Key"].ToString(), out value);

但是,我确实需要考虑 null。其中,如果 string 失败,默认 out 将返回 null。除了我注意到 int.TryParse 不适用于:

int? value = null;
int.TryParse(Session["Key"].ToString(), out value);

那么您如何尝试解析,如果失败则导致 null?

我找到了这个 question微软开发者网络规定:

When this method returns, contains the signed integer value equivalent of the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the string parameter is null or String.Empty, is not of the correct format, or represents a number less than Min Value or greater than Max Value. This parameter is passed uninitialized.

这很明显,如果 int.TryParse 失败,整数将保持零值。在我的使用实例中,零可能是一个有效值。所以我需要 null,有什么想法吗?

最佳答案

当然;利用 int.TryParse 的返回值(转换成功与否返回):

int? retValue = null;
int parsedValue = 0;

if (int.TryParse(Session["Key"].ToString(), out parsedValue))
    retValue = parsedValue;
else
    retValue = null;

return retValue;

我承认有点冗长,但您可以将其包装在一个函数中。

关于c# - 哇,什么是 TryParse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26855032/

相关文章:

C# 正则表达式 "+"组返回空字符串

javascript - 根据输入调用函数

asp.net - ASP.NET Webforms 中的部分 SSL 无需更改 IIS 配置

c# - 获取用于转换为 base 64 字符串的图像路径

c# - asp net core app出现MSB3277怎么办

c# - 我可以向功能区添加自定义控件吗?

c# - 动态选择EntityFramework和System.Linq.Dynamic

c# - Owin 使用外部表单例份验证 cookie

asp.net - Windows 身份验证多次请求

asp.net-mvc - 如何将 ASP.Net MVC 路由段中的 1 或 0 映射到 bool 操作方法输入参数