如何分析一个字符串转换为可空INT转换为、字符串、INT

2023-09-02 01:31:47 作者:肆情

我想解析字符串转换成在C#中为空的int类型。 IE浏览器。我想找回的字符串或无论是int值零,如果它不能被解析。

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建议,我也知道这一点,但它的工作差不多。我更想知道,如果有一个内置的架构方法,将直接解析成一个可为空中断?

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?

推荐答案

Int32.TryParse可能是一个稍微简单:

Int32.TryParse is probably a tad easier:

public static int? ToNullableInt32(this string s)
{
    int i;
    if (Int32.TryParse(s, out i)) return i;
    return null;
}

修改 @Glenn Int32.TryParse是内置到框架。它和Int32.Parse是的在的方法来解析字符串整数。

Edit @Glenn Int32.TryParse is "built into the framework". It and Int32.Parse are the way to parse strings to ints.

 
精彩推荐