如何将字符串解析为可空的int

本文翻译自:How to parse a string into a nullable int

I'm wanting to parse a string into a nullable int in C#. 我想在C#中将字符串解析为可以为空的int。 ie. 即。 I want to get back either the int value of the string or null if it can't be parsed. 我想要返回字符串的int值,如果无法解析,则返回null。

I was kind of hoping that this would work 我有点希望这会奏效

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? 有没有更好的方法呢?

EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. 编辑:感谢TryParse的建议,我确实知道这一点,但它的结果大致相同。 I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? 我更感兴趣的是知道是否有一个内置的框架方法可以直接解析为可以为空的int?


#1楼

参考:https://stackoom.com/question/bIi/如何将字符串解析为可空的int


#2楼

Using delegates, the following code is able to provide reusability if you find yourself needing the nullable parsing for more than one structure type. 使用委托,如果您发现自己需要对多个结构类型进行可空的解析,则以下代码能够提供可重用性。 I've shown both the .Parse() and .TryParse() versions here. 我在这里展示了.Parse()和.TryParse()版本。

This is an example usage: 这是一个示例用法:

NullableParser.TryParseInt(ViewState["Id"] as string);

And here is the code that gets you there... 以下是让你在那里的代码......

public class NullableParser
  {
    public delegate T ParseDelegate<T>(string input) where T : struct;
    public delegate bool TryParseDelegate<T>(string input, out T outtie) where T : struct;
    private static T? Parse<T>(string input, ParseDelegate<T> DelegateTheParse) where T : struct
    {
      if (string.IsNullOrEmpty(input)) return null;
      return DelegateTheParse(input);
    }
    private static T? TryParse<T>(string input, TryParseDelegate<T> DelegateTheTryParse) where T : struct
    {
      T x;
      if (DelegateTheTryParse(input, out x)) return x;
      return null;
    }
    public static int? ParseInt(string input)
    {
      return Parse<int>(input, new ParseDelegate<int>(int.Parse));
    }
    public static int? TryParseInt(string input)
    {
      return TryParse<int>(input, new TryParseDelegate<int>(int.TryParse));
    }
    public static bool? TryParseBool(string input)
    {
      return TryParse<bool>(input, new TryParseDelegate<bool>(bool.TryParse));
    }
    public static DateTime? TryParseDateTime(string input)
    {
      return TryParse<DateTime>(input, new TryParseDelegate<DateTime>(DateTime.TryParse));
    }
  }

#3楼

I found and adapted some code for a Generic NullableParser class. 我找到并修改了Generic NullableParser类的一些代码。 The full code is on my blog Nullable TryParse 完整的代码在我的博客Nullable TryParse上

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace SomeNamespace
{
    /// <summary>
    /// A parser for nullable types. Will return null when parsing fails.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    ///
    public static class NullableParser<T> where T : struct
    {
        public delegate bool TryParseDelegate(string s, out T result);
        /// <summary>
        /// A generic Nullable Parser. Supports parsing of all types that implements the tryParse method;
        /// </summary>
        /// <param name="text">Text to be parsed</param>
        /// <param name="result">Value is true for parse succeeded</param>
        /// <returns>bool</returns>
        public static bool TryParse(string s, out Nullable<T> result)
        {
            bool success = false;
            try
            {
                if (string.IsNullOrEmpty(s))
                {
                    result = null;
                    success = true;
                }
                else
                {
                    IConvertible convertableString = s as IConvertible;
                    if (convertableString != null)
                    {
                        result = new Nullable<T>((T)convertableString.ToType(typeof(T),
                            CultureInfo.CurrentCulture));
                        success = true;
                    }
                    else
                    {
                        success = false;
                        result = null;
                    }
                }
            }
            catch
            {
                success = false;
                result = null;
            }
            return success;
        }
    }
}

#4楼

This solution is generic without reflection overhead. 此解决方案通用,没有反射开销。

public static Nullable<T> ParseNullable<T>(string s, Func<string, T> parser) where T : struct
{
    if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) return null;
    else return parser(s);
}

static void Main(string[] args)
{
    Nullable<int> i = ParseNullable("-1", int.Parse);
    Nullable<float> dt = ParseNullable("3.14", float.Parse);
}

#5楼

I had this problem I ended up with this (after all, an if and 2 return s is soo long-winded!): 我有这个问题我最终得到了这个(毕竟, if和2 return s太啰嗦了!):

int? ParseNInt (string val)
{
    int i;
    return int.TryParse (val, out i) ? (int?) i : null;
}

On a more serious note, try not to mix int , which is a C# keyword, with Int32 , which is a .NET Framework BCL type - although it works, it just makes code look messy. 更严重的是,尽量不要将int (这是一个C#关键字)与Int32 (一种.NET Framework BCL类型)混合使用 - 尽管它有效,但它只会让代码看起来很乱。


#6楼

I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? 我更感兴趣的是知道是否有一个内置的框架方法可以直接解析为可以为空的int?

There isn't. 没有。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值