使用泛型改进和实现?

时间:2015-04-17 11:02:33

标签: c# generics

我需要编写采用字符串值的方法,并尝试将其解析为基本数据类型。如果解析不成功,则方法应返回null。

我写了以下方法,但我觉得必须有办法减少冗余。我知道泛型,但由于每种数据类型的解析都不同,使用泛型似乎很复杂。

如何改进以下代码?

public static DateTime? GetNullableDateTime(string input)
{
    DateTime returnValue;
    bool parsingSuccessful = DateTime.TryParseExact(input, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out returnValue);
    return parsingSuccessful ? returnValue : (DateTime?)null;
}

public static decimal? GetNullableDecimal(string input)
{
    decimal returnValue;
    bool parsingSuccessful = decimal.TryParse(input, out returnValue);
    return parsingSuccessful ? returnValue : (decimal?)null;
}

1 个答案:

答案 0 :(得分:1)

参见提供的示例。这只是多种方式中的一种,最终取决于您预期的数据类型。

你绝对应该包含错误处理。

public void Test()
{
    Console.WriteLine(Parse<int>("1"));
    Console.WriteLine(Parse<decimal>("2"));
    Console.WriteLine(Parse<DateTime>("2015-04-20"));
}

public static T Parse<T>(string input)
{
    TypeConverter foo = TypeDescriptor.GetConverter(typeof(T));
    return (T)(foo.ConvertFromInvariantString(input));
}