int.TryParse = null 如果不是数字?
如果无法将字符串解析为 int,是否有某种方法返回 null?
with:
public .... , string? categoryID)
{
int.TryParse(categoryID, out categoryID);
得到“无法从‘out string’转换为‘out int’
该怎么办?
编辑:
方法
由于asp.net约束而不再相关是解决问题/M的
is there some way of return null if it can't parse a string to int?
with:
public .... , string? categoryID)
{
int.TryParse(categoryID, out categoryID);
getting "cannot convert from 'out string' to 'out int'
what to do?
EDIT:
No longer relevant because of asp.net constraints is the way to solve problem
/M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
首先,为什么要尝试将字符串解析为 int 并将结果粘贴回字符串中?
方法签名是
这样的,因此您必须提供一个
int
类型的变量作为第二个参数。这也意味着如果解析失败,您将不会得到null
,而是该方法将简单地返回false
。但你可以轻松地将它们拼凑在一起:First of all, why are you trying to parse a string to an int and stick the result back into a string?
The method signature is
so you have to give a variable of type
int
as second argument. This also means that you won't getnull
if parsing fails, instead the method will simply returnfalse
. But you can easily piece that together:这是
Int32.TryParse
的正确用法:Here's a proper use of
Int32.TryParse
:这个怎么样?
How about this?
最简单且一行行...
它有效,因为它是从左到右评估的。空不是那么容易。
Simplest and one-liner...
It works 'cause it's evaluated left to right. Null not so easy.
如果字符串无法解析,
TryParse
将返回 false。您可以使用此事实返回解析的值或 null。无论如何,我猜你打算从你的方法返回int?
,那么它会是这样的:TryParse
will return false if the string can't be parsed. You can use this fact to return either the parsed value, or null. Anyway I guess that you are intending to returnint?
from your method, then it would be something like this:你想做这样的事情吗?
Do you want to do something like this?
Int 是一种值类型,这意味着不存在 null int 之类的东西。所以不,TryParse 永远不会改变 out 参数,使其为空。
但您遇到的问题是,当 TryParse 需要整数时,您将字符串传递给 TryParse 的 out 参数。
你需要这样的东西......
Int is a value type which means there is no such thing as a null int. So no, TryParse will never alter the out parameter so that it is null.
But the problem you're having is you're passing a string to the out parameter of TryParse when its expecting an integer.
You need something like this...
**这个答案被否决了很多**
尽管这是一种可能的解决方案,但从性能角度来看,它是一个糟糕的解决方案,并且可能不是一个好的编程选择。
我不会删除它,因为我猜很多程序员可能没有意识到这一点,所以这里是一个如何不做事情的例子:
使用 try 和 catch
** this answer was down-voted a lot **
Although it is a possible solution - it is a bad one performance wise, and probably not a good programming choice.
I will not delete it, as I guess many programmers might not be aware of this, so here is an example how not to do things:
use try and catch