我有一个包含特定整数值的 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/