2015-04-17 137 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