簡體   English   中英

在C#中將string.Empty轉換為(generic)T?

[英]Cast string.Empty to (generic) T in C#?

我有一個實用程序方法,它使用簽名從舊的.INI配置類型文件返回一個強類型值

internal static T GetIniSetting<T>(string config, string key, T defVal = default(T))

我希望字符串是特殊的,因為我希望defaultValue的默認值是string.Empty ,而不是default(string) (即null),在編碼器沒有指定默認值的情況下。

if (cantFindValueInIniFile == true)
{
    if ((typeof(T) == typeof(string)) && (defaultValue == null))
    {
        // *** Code needed here - Cannot convert string to <T>***
        return (T)string.Empty; 
    }
    return defaultValue;
}

我嘗試過強制轉換,而as關鍵字也無濟於事。

'hacky'方式:

return (T)(object)string.Empty; 

筆記:

  • 非常安全,因為您有檢查前提條件。
  • 對引用類型的性能損失不明顯。

你必須這樣做: (T)(object)(string.Empty)

此外,次要優化是將其存儲在靜態只讀字符串字段中,這樣您就不必每次使用一次參數(而不是每個方法調用)進行一次轉換

如果我沒有弄錯,GetIniSetting中的最后一個參數是可選的,只有當你沒有為它提供任何東西時你才會得到默認值(字符串)。 因此,使用string.Empty作為默認字符串值,使調用如下:

string value = GetIniSetting<string>(config, key, string.Empty);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM