如何分析一个字符串转换为可空INT [英] How to parse a string into a nullable int

查看:422
本文介绍了如何分析一个字符串转换为可空INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析字符串转换成在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.

这篇关于如何分析一个字符串转换为可空INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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