如果你想要一個實現方法具d返回不同的信息類型,然後我會使用泛型:
public static T GetInfo<T>(string name);
// This can be called as following:
string name = GetInfo<string>("name");
int salary = GetInfo<int>("salary");
還有一個問題,雖然:Console.ReadLine
返回string
,而我們的方法可以返回任何類型。它如何將字符串轉換爲其'目標'類型?您可以檢查T
併爲您想要支持的所有類型編寫自定義邏輯,但這很麻煩而且很脆弱。更好的方法是讓調用者傳遞一個知道如何將字符串轉換成特定類型的一個小功能:
public static T GetInfo<T>(string name, Func<string, T> convert);
// This can be called as following:
string name = GetInfo<string>("name", s => s);
int salary = GetInfo<int>("salary", int.Parse);
現在,你如何實現一個方法是什麼?
public static T GetInfo<T>(string name, Func<string, T> convert)
{
Console.WriteLine("Please enter " + name);
string input = Console.ReadLine();
return convert(input);
}
的幾個注意事項:
- 類型參數往往只是命名爲
T
,但我覺得它非常有用,給他們更多的描述性的名稱,如TInfo
。
<string>
和<int>
部分可以在第二個例子中省略,因爲編譯器有足夠的信息來推斷它們的類型。
- 我已經離開了我們的錯誤處理,以保持示例簡潔。但是,在生產代碼中,您會想出一個處理無效輸入的策略。
所以你想你的方法返回一個字符串或一個int? –
使用C#7 +元組:https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/#user-content-tuples。 –
這個尖叫XY問題(如果你不知道這意味着什麼,Google它,我沒有手機上的鏈接)。你想用這個做什麼? –