7

TryParse为以下Nullable类型编写了重载的静态方法:int?, short?, long?, double?, DateTime?, decimal?, float?, bool?,byte?char?. 下面是一些实现:

protected static bool TryParse(string input, out int? value)
{
    int outValue;
    bool result = Int32.TryParse(input, out outValue);
    value = outValue;
    return result;
}

protected static bool TryParse(string input, out short? value)
{
    short outValue;
    bool result = Int16.TryParse(input, out outValue);
    value = outValue;
    return result;
}

protected static bool TryParse(string input, out long? value)
{
    long outValue;
    bool result = Int64.TryParse(input, out outValue);
    value = outValue;
    return result;
}

每种方法的逻辑都是相同的,只是它们使用不同的类型。难道不能使用泛型,这样我就不需要那么多冗余代码了吗?签名将如下所示:

bool TryParse<T>(string input, out T value);

谢谢

4

3 回答 3

9

难道不能使用泛型,这样我就不需要那么多冗余代码了吗?

您可以通过反射来做到这一点,但这会相对较慢。否则,您可以创建一个从类型到“用于该类型的方法”的映射,但这会非常难看。除此之外,它永远不会是真正的泛型——它只适用于提供TryParse正确签名方法的类型,而这在编译时是未知的。

顺便说一句,我个人会考虑改变签名和行为。目前,即使 of 的类型value是可空的,它也永远不会在方法的末尾有空值,即使你 return false。为什么不将返回值作为解析操作的结果,null失败返回呢?

protected static long? TryParseInt64(string input)
{
    long outValue;
    return Int64.TryParse(input, out outValue) ? (long?) outValue : null;
}
于 2013-05-31T07:07:54.310 回答
8

您可以使用以下通用扩展方法,

public static Nullable<TSource> TryParse<TSource>(this string input) where TSource : struct
{
    try
    {
        var result = Convert.ChangeType(input, typeof(TSource));
        if (result != null)
        {
            return (TSource)result;
        }
        return null;
    }
    catch (Exception)
    {
        return null;
    }
}

以下调用将返回可空解析类型。

string s = "510";
int? test = s.TryParse<int>();
//TryParse Returns 510 and stored in variable test.

string s = "TestInt";
int? test = s.TryParse<int>();
//TryParse Returns null and stored in variable test.
于 2013-05-31T07:30:37.397 回答
4

顺便说一句,您可以重构您的代码:

public static bool TryParse(string input, out int? value)
{
    return TryParse(input, Int32.TryParse, out value);
}

protected static bool TryParse(string input, out short? value)
{
    return TryParse(input, Int16.TryParse, out value);
}

protected static bool TryParse(string input, out long? value)
{
    return TryParse(input, Int64.TryParse, out value);
}

private static bool TryParse<T>(string input, TryParseFunc<T> tryParse, out T? value)
    where T : struct
{
    T outValue;
    bool result = tryParse(input, out outValue);
    value = outValue;
    return result;
}

private delegate bool TryParseFunc<T>(string input, out T value);
于 2013-05-31T07:24:51.507 回答