C# 优雅的 TryParse

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10693231/
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-09 14:50:35  来源:igfitidea点击:

Elegant TryParse

c#

提问by Antonio Bakula

I feel that every time I use TryParsethat it results in somewhat ugly code. Mainly I am using it this way:

我觉得每次使用TryParse它都会导致代码有点难看。我主要是这样使用它的:

int value;
if (!int.TryParse(someStringValue, out value))
{
    value = 0;
}

Is there some more elegant solution for parsing all basic data types, to be specific is there a way to do fail safe parsing in one line? By fail safe I assume setting default value if parsing fails without exception.

是否有一些更优雅的解决方案来解析所有基本数据类型,具体来说有没有办法在一行中进行故障安全解析?通过故障安全,如果解析无一例外地失败,我假设设置默认值。

By the way, this is for cases where I must do some action even if parsing fails, just using the default value.

顺便说一句,这是针对即使解析失败我也必须执行某些操作的情况,只需使用默认值即可。

采纳答案by dav_i

This is valid and you may prefer it if you have a liking for single-liners:

这是有效的,如果您喜欢单线,您可能更喜欢它:

int i = int.TryParse(s, out i) ? i : 42;

This sets the value of ito 42if it cannot parse the string s, otherwise it sets i = i.

这台价值i42,如果它不能解析字符串s,否则它设置i = i

回答by skarmats

You can write your own methods for a solution that suits you better. I stumbled upon the Maybeclass that wraps the TryParsemethods a while ago.

您可以为更适合您的解决方案编写自己的方法。不久前我偶然发现了Maybe包装TryParse方法的类。

int? value = Maybe.ToInt("123");

if (value == null)
{
    // not a number
}
else
{
    // use value.Value
}

or specify the default value in-line:

或内联指定默认值:

int value = Maybe.ToInt("123") ?? 0;

Observe the distinction between Nullable<int>/int?and int.

观察Nullable<int>/int?和之间的区别int

See http://www.kodefuguru.com/post/2010/06/24/TryParse-vs-Convert.aspxfor more info

有关更多信息,请参阅http://www.kodefuguru.com/post/2010/06/24/TryParse-vs-Convert.aspx

回答by yamen

You could use TypeDescriptor instead:

您可以改用 TypeDescriptor:

public T Convert<T>(string input, T defaultVal)
{
    var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
    if(converter != null)
    {
        return (T)converter.ConvertFromString(input);
    }
    return defaultVal;
}

public T Convert<T>(string input)
{
    return Convert(input, default(T));
}

You could constrain Tto struct and use Nullablealso (as per @skarmats answer).

您也可以限制T结构和使用Nullable(根据@skarmats 的回答)。

回答by user287107

how about a direct extension method?

直接扩展方法怎么样?

public class Extensions
{
    public static int? TryParse(string this Source)
    {
        if(int.tryparse .... 
    }

}

usage:

用法:

v = "234".TryParse() ?? 0

回答by Jason Williams

In your particular example, you can do this:

在您的特定示例中,您可以这样做:

int value; 
int.TryParse(someStringValue, out value);

...because Int32.TryParse() is documented as setting value=0if it fails the parse.

...因为 Int32.TryParse()value=0在解析失败时被记录为设置。

回答by Antonio Bakula

There is a nice little feature in C# 6C# 7, Declaration expressions, so in C# 7 instead of:

C# 6C# 7 中有一个很好的小特性,声明表达式,所以在 C# 7 中而不是:

int x;
if (int.TryParse("123", out x))
{
  DoSomethingWithX(x);
}

we can use:

我们可以用:

if (int.TryParse("123", out int x))
{
  DoSomethingWithX(x);
}

Nice enough for me :)

对我来说已经足够好了:)

回答by Richard Dalton

This is one of the nice surprises for C# developers who try F#. The TryParse method returns a tuple containing both the bool and the value.

对于尝试 F# 的 C# 开发人员来说,这是一个不错的惊喜之一。TryParse 方法返回一个包含 bool 和值的元组。

回答by Francesco Moroni

using C# 7 in single line

在单行中使用 C# 7

int.TryParse(s, out var i) ? i : (int?)null;

Example Method:

示例方法:

public static int? TryParseSafe(string s)
{
    return int.TryParse(s, out var i) ? i : (int?)null;
}