如果无法将字符串解析为int,是否有一些返回null的方法?
有:
public .... , string? categoryID)
{
int.TryParse(categoryID, out categoryID);
Run Code Online (Sandbox Code Playgroud)
得到"无法从'输出字符串'转换为'输出int'
该怎么办?
编辑:
由于asp.net约束不再相关是解决问题的方法
/ M
Joe*_*oey 27
首先,为什么要尝试将字符串解析为int并将结果粘贴回字符串?
方法签名是
bool int.TryParse(string, out int)
Run Code Online (Sandbox Code Playgroud)
所以你必须给出一个类型的变量int
作为第二个参数.这也意味着null
如果解析失败,您将无法获得,而是方法将返回false
.但你可以很容易地把它拼凑在一起:
int? TryParse2(string s) {
int i;
if (!int.TryParse(s, out i)) {
return null;
} else {
return i;
}
}
Run Code Online (Sandbox Code Playgroud)
jas*_*son 14
这是一个正确使用Int32.TryParse
:
int? value;
int dummy;
if(Int32.TryParse(categoryID, out dummy)) {
value = dummy;
}
else {
value = null;
}
return value;
Run Code Online (Sandbox Code Playgroud)
Dig*_*mad 10
这个怎么样?
public int? ParseToNull(string categoryId)
{
int id;
return int.TryParse(categoryId, out id) ? (int?)id : null;
}
Run Code Online (Sandbox Code Playgroud)