我想在c#中解析一个字符串为可空int。ie。我想返回字符串的int值或null,如果它不能被解析。

我有点希望这能起作用

int? val = stringVal as int?;

但这行不通,我现在要做的是写这个扩展方法

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

有更好的办法吗?

编辑:感谢TryParse的建议,我确实知道这一点,但它的工作原理是一样的。我更感兴趣的是知道是否有一个内置的框架方法,将直接解析成一个可空的int?


当前回答

我觉得我的解决方案是一个非常干净和漂亮的解决方案:

public static T? NullableParse<T>(string s) where T : struct
{
    try
    {
        return (T)typeof(T).GetMethod("Parse", new[] {typeof(string)}).Invoke(null, new[] { s });
    }
    catch (Exception)
    {
        return null;
    }
}

当然,这是一个通用的解决方案,只需要泛型参数有一个静态方法“Parse(string)”。这适用于数字,布尔值,日期时间等。

其他回答

如果没有必要,就不要使用异常——开销太大了。

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

我知道这是个老话题了,但你就不能简单地:

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

?

我建议以下扩展方法将字符串解析为int值,并在解析不可能的情况下定义默认值:

public static int ParseInt(this string value, int defaultIntValue = 0)
        {
            return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;
        }

public static int? ParseNullableInt(this string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;

            return value.ParseInt();
        }

我想出了这个方法,它满足了我的要求(我希望我的扩展方法尽可能地模拟框架的TryParse的返回,但是没有try{} catch{}块,并且没有编译器抱怨在框架方法中推断出可空类型)

private static bool TryParseNullableInt(this string s, out int? result)
{
    int i;
    result = int.TryParse(s, out i) ? (int?)i : null;
    return result != null;
}

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

我遇到了这个问题,我最终得到了这个(毕竟,一个if和2返回是如此冗长!):

int? ToNullableInt (string val)
    => int.TryParse (val, out var i) ? (int?) i : null;

更严肃的一点是,尽量不要把int (c#关键字)和Int32 (. net Framework BCL类型)混在一起——尽管它可以工作,但它只会让代码看起来很乱。