如果不是数字,则int.TryParse = null? [英] int.TryParse = null if not numeric?

查看:173
本文介绍了如果不是数字,则int.TryParse = null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果无法将字符串解析为int,是否有某种返回null的方法?

is there some way of return null if it can't parse a string to int?

具有:

public .... , string? categoryID) 
{
int.TryParse(categoryID, out categoryID);

获取无法从'out string'转换为'out int'

getting "cannot convert from 'out string' to 'out int'

该怎么办?

由于asp.net限制而不再相关是解决问题的方法

No longer relevant because of asp.net constraints is the way to solve problem

/M

推荐答案

首先,为什么要尝试将字符串解析为int并将结果粘贴回字符串中?

First of all, why are you trying to parse a string to an int and stick the result back into a string?

方法签名是

bool int.TryParse(string, out int)

,因此您必须提供类型为int的变量作为第二个参数.这也意味着,如果解析失败,您将不会得到null,相反,该方法只会返回false.但是您可以轻松地将它们拼凑在一起:

so you have to give a variable of type int as second argument. This also means that you won't get null if parsing fails, instead the method will simply return false. But you can easily piece that together:

int? TryParse2(string s) {
    int i;
    if (!int.TryParse(s, out i)) {
        return null;
    } else {
        return i;
    }
}

这篇关于如果不是数字,则int.TryParse = null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆