0
我需要编写带有字符串值的方法,并尝试将其解析为基本数据类型。如果解析不成功,则方法应该返回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;
}
参见http://stackoverflow.com/questions/2961656/generic-tryparse – mbdavis
@mbdavis,converter.ConvertFromString(输入)是很原始的。例如,你不能指定日期格式。 –
我不认为如果你想达到这种控制水平,你可以做出任何有意义的修改。无论如何,它们都是非常小的代码块,你看到了多少冗余?你可以使用接口来为不同的对象定义一个解析方法,它可以将类型转换为可空对象,但它会让你获得比原来更多的代码... – mbdavis