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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:56:17  来源:igfitidea点击:

How to parse a string into a nullable int

提问by Glenn Slaven

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.

我想在 C# 中将字符串解析为可为空的 int。IE。如果无法解析,我想取回字符串的 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. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

编辑:感谢 TryParse 的建议,我确实知道这一点,但结果大致相同。我更想知道是否有一个内置的框架方法可以直接解析为可空的 int?

采纳答案by Matt Hamilton

int.TryParseis probably a tad easier:

int.TryParse可能更容易一点:

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

Edit@Glenn int.TryParseis "built into the framework". It and int.Parseare theway to parse strings to ints.

编辑@Glennint.TryParse是“内置于框架中”。它int.Parse字符串解析为整数的方法。

回答by Joseph Daigle

Try this:

尝试这个:

public static int? ParseNullableInt(this string value)
{
    int intValue;
    if (int.TryParse(value, out intValue))
        return intValue;
    return null;
}

回答by McKenzieG1

You can do this in one line, using the conditional operator and the fact that you can cast nullto a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of TryParse):

您可以在一行中执行此操作,使用条件运算符以及可以强制null转换为可为空类型的事实(两行,如果您没有预先存在的 int,则可以将其重用于 的输出TryParse):

Pre C#7:

C#7 前:

int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null;

With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.

使用 C#7 的更新语法,允许您在方法调用中声明输出变量,这变得更加简单。

int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;

回答by Murph

You should neveruse an exception if you don't have to - the overhead is horrible.

如果你没有必要,你永远不应该使用异常 - 开销是可怕的。

The variations on TryParse solve the problem - if you want to get creative (to make your code look more elegant) you could probably do something with an extension method in 3.5 but the code would be more or less the same.

TryParse 的变体解决了这个问题——如果你想发挥创意(让你的代码看起来更优雅),你可能可以用 3.5 中的扩展方法做一些事情,但代码或多或少是相同的。

回答by Duckboy

[Updatedto use modern C# as per @sblom's suggestion]

[根据@sblom 的建议更新为使用现代 C#]

I had this problem and I ended up with this (after all, an ifand 2 returns is soo long-winded!):

我遇到了这个问题,最终得到了这个(毕竟, anif和 2 returns 太啰嗦了!):

int? ToNullableInt (string val)
    => int.TryParse (val, out var 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.

更严肃地说,尽量不要将intC# 关键字 与Int32.NET Framework BCL 类型混合使用 - 尽管它可以工作,但只会使代码看起来很混乱。

回答by Orion Edwards

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.

没有。

回答by umbyersw

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));
    }
  }

回答by John Dauphine

I found and adapted some code for a Generic NullableParser class. The full code is on my blog Nullable TryParse

我为 Generic NullableParser 类找到并修改了一些代码。完整代码在我的博客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;
        }
    }
}

回答by Leigh Bowers

I realise this is an old topic, but can't you simply:

我意识到这是一个古老的话题,但你不能简单地:

(Nullable<int>)int.Parse(stringVal);

?

?

回答by Daniel Ballinger

The following should work for any struct type. It is based off code by Matt Manela from MSDN forums. As Murph points out the exception handling could be expensive compared to using the Types dedicated TryParse method.

以下应该适用于任何结构类型。它基于来自 MSDN 论坛的 Matt Manela 的代码。正如 Murph 指出的那样,与使用 Types 专用的 TryParse 方法相比,异常处理可能会很昂贵。

        public static bool TryParseStruct<T>(this string value, out Nullable<T> result)
            where T: struct 
        {
            if (string.IsNullOrEmpty(value))
            {
                result = new Nullable<T>();

                return true;
            }

            result = default(T);
            try
            {
                IConvertible convertibleString = (IConvertible)value;
                result = new Nullable<T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));
            }
            catch(InvalidCastException)
            {
                return false;
            }
            catch (FormatException)
            {
                return false;
            }

           return true;
        }

These were the basic test cases I used.

这些是我使用的基本测试用例。

        string parseOne = "1";
        int? resultOne;
        bool successOne = parseOne.TryParseStruct<int>(out resultOne);
        Assert.IsTrue(successOne);
        Assert.AreEqual(1, resultOne);

        string parseEmpty = string.Empty;
        int? resultEmpty;
        bool successEmpty = parseEmpty.TryParseStruct<int>(out resultEmpty);
        Assert.IsTrue(successEmpty);
        Assert.IsFalse(resultEmpty.HasValue);

        string parseNull = null;
        int? resultNull;
        bool successNull = parseNull.TryParseStruct<int>(out resultNull);
        Assert.IsTrue(successNull);
        Assert.IsFalse(resultNull.HasValue);

        string parseInvalid = "FooBar";
        int? resultInvalid;
        bool successInvalid = parseInvalid.TryParseStruct<int>(out resultInvalid);
        Assert.IsFalse(successInvalid);