一般的TryParse Nullable类型

Dav*_*New 6 .net c# generics parsing type-conversion

我已经写了重载的静态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;
}
Run Code Online (Sandbox Code Playgroud)

每种方法的逻辑都是相同的,只是它们使用不同的类型.是不是可以使用泛型,这样我就不需要那么多的冗余代码?签名看起来像这样:

bool TryParse<T>(string input, out T value);
Run Code Online (Sandbox Code Playgroud)

谢谢

Jon*_*eet 9

是不是可以使用泛型,这样我就不需要那么多的冗余代码?

你可以用反射来做,但那会比较慢.否则,您可以创建一个从类型到"用于该类型的方法"的映射,但它会非常难看.除了其他任何东西,它永远不会是真正的通用 - 它只适用于提供TryParse正确签名方法的类型,这在编译时是无法知道的.

顺便说一句,我个人会考虑改变签名和行为.目前即使类型value是可空的,它也不会在方法结束时具有空值,即使您返回也是如此false.为什么不将返回值作为解析操作的结果,返回null失败?

protected static long? TryParseInt64(string input)
{
    long outValue;
    return Int64.TryParse(input, out outValue) ? (long?) outValue : null;
}
Run Code Online (Sandbox Code Playgroud)


pet*_*jan 7

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下调用将返回可为空的解析类型.

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.
Run Code Online (Sandbox Code Playgroud)