2009-11-04 32 views
1

我想爲幾種類型(如long,TimeSpan和DateTime)提供通用函數。使用基於typeof內部通用函數的特定類型

public static T Parse<T>(string text) 
{ 
    T store; 

    if(typeof(T) == typeof(TimeSpan) 
     store = (T)((object) new TimeSpan(0, 1, 0)); 
    else 
    { 
     T.tryParse(text, out store); 
    } 
    return store; 
} 

有沒有比雙T /物體表演更好的方法?

t.tryParse不能編譯,我該怎麼做到類似的東西?

+0

什麼是編譯錯誤? – Ucodia 2009-11-04 11:01:48

回答

6

我覺得在這種情況下最好有一個重載的方法。關於調用TryParse - Int32.TryParseInt64.TryParse等是完全不同的方法,這也會讓你遠離雙重陣容(我同意它很醜,但不幸難以避免)。這也意味着你會指定哪些類型可以真正支持。

一種選擇是使用Dictionary<Type, Func<string, object>>

// Add some error checking, obviously :) 
Func<string, object> parser = parsers[typeof(T)]; 
return (T) parser(form.Text); 

然後設置字典的東西,如:

static readonly Dictionary<Type, Func<string, object>> parsers = 
    new Dictionary<Type, Func<string, object>>() 
{ 
    { typeof(int), x => int.Parse(x) }, 
    { typeof(TimeSpan) x => new TimeSpan(0, 1, 0) }, 
    ... 
} 

如果你想使用TryParse而不是Parse,你需要由於使用了輸出參數(在Func/Action中不支持)創建您自己的代表類型。在這一點上,生活變得有點困難。

順便說一句,你爲什麼使用out參數而不是返回值?

+0

解析函數的功能是匹配TryParse調用中的輸出。我的問題只有一個實際的代碼,它返回一個表示TryParse結果的布爾值。 我會很快看到答案,謝謝。 – hultqvist 2009-11-04 11:58:20

+0

爲了回答您的問題,刪除了該問題以保持我的問題爲重點。 – hultqvist 2009-11-04 12:02:56