2015-04-17 134 views
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; 
} 
+2

参见http://stackoverflow.com/questions/2961656/generic-tryparse – mbdavis

+0

@mbdavis,converter.ConvertFromString(输入)是很原始的。例如,你不能指定日期格式。 –

+0

我不认为如果你想达到这种控制水平,你可以做出任何有意义的修改。无论如何,它们都是非常小的代码块,你看到了多少冗余?你可以使用接口来为不同的对象定义一个解析方法,它可以将类型转换为可空对象,但它会让你获得比原来更多的代码... – mbdavis

回答

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)); 
} 
+0

http://coding.grax.com/2013/04/generic- tryparse.html这是我在一个类似于此的通用TryParse上做的博客文章。 – Grax