问题描述
我想在 C# 中将字符串解析为可为空的 int.IE.如果无法解析,我想取回字符串的 int 值或 null.
I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.
我有点希望这会奏效
int? val = stringVal as int?;
但这行不通,所以我现在的做法是我写了这个扩展方法
But that won't work, so the way I'm doing it now is I've written this extension method
public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
有没有更好的方法来做到这一点?
Is there a better way of doing this?
感谢 TryParse 的建议,我确实知道这一点,但结果大致相同.我更想知道是否有内置的框架方法可以直接解析为可为空的 int?
Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?
推荐答案
int.TryParse
可能更容易一些:
public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}
编辑 @Glenn int.TryParse
内置于框架中".它和 int.Parse
是将字符串解析为整数的方式.
Edit @Glenn int.TryParse
is "built into the framework". It and int.Parse
are the way to parse strings to ints.
这篇关于如何将字符串解析为可以为空的 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!