English 中文(简体)
优优试
原标题:Elegant TryParse
  • 时间:2012-05-21 21:58:22
  •  标签:
  • c#

我觉得每次我使用TryParse 都会导致代码有些丑陋。

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

对所有基本数据类型进行解析是否有更优雅的解决方案, 具体地说, 是否有一种方法可以在一条行中进行安全解析失败? 如果解析失败, 安全解析失败, 我假设我设定默认值, 如果无例外地解析失败 。

顺便说一下,这是在一些情况下,我必须做一些行动,即使分析失败,只要使用默认值即可。

最佳回答

这是有效的,如果你喜欢单航道的话,你可能会更喜欢它:

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

如果无法解析字符串 , 则将 的值设置为 42 , 否则它会设置 = i

问题回答

直接推广的方法怎么样?

public static class Extensions
{
    public static int? TryParse(this string Source)
    {
        int result;
        if (int.TryParse(Source, out result))
            return result;
        else

            return null;
    }
}

或者在单行中使用新的 c# 语法 :

public static int? TryParse(this string Source) => int.TryParse(Source, out int result) ? result : (int?)null;

使用量 :

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

您可以为适合您的解决方案写入自己的方法 。 我刚刚偶然发现了覆盖 < code> TryParse < /code > 方法的 < code> 类 。

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

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

或指定默认值的内行 :

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

观察 Nullallble<int> / int? int 之间的区别。

rel=“noreferrerr'>http://www.kodefugru.com/post/2010/06/24/TryParse-vs-convert.aspx ,以了解更多信息。

C# 6 C# 7, < a href="https://roslyn.codeplex.com/wikipage? title=Language% 20Fatrial%20 Status & amp; rerefertingTitle=Documentation" rel=“noreferr' > 宣言表达式 ,所以在C# 7,而不是:

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

我们可以使用:

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

对我而言已经足够好了:)

单行使用C#7

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

示例方法:

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

在您的具体例子中,您可以做到:

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

...因为 Int32. TryParse () 被记录为设置 value=0 , 如果它无法解析的话 。

您可以使用类型描述符代替 :

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

您可以将 T 限制在结构上, 并使用 Nullallble (根据@skarmats 回答) 。

我对><这个答案 稍有改进,它使扩展法和TryConvert扩展法在下面的片段:

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

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

public static bool TryConvert<T>(this string input, T defaultVal, out T result)
{
    try
    {
        result = Convert(input, defaultVal);
        return true;
    }
    catch (Exception exception)
    {
        result = defaultVal;
        return string.IsNullOrEmpty(input);
    }
}

然后我们就可以把它用得像片片段一样

 if (someValue.TryConvert(1, out var result))
 {

 }

结果 数据类型自动取决于默认值Val

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.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...