簡體   English   中英

泛型類型nullable和ToString

[英]Generic type nullable and ToString

在我的方法中,我想處理可空的整數值。

public String FormatValue(Int32? item)
{
 if (item.HasValue==false) return "";
 return item.Value.ToString("### ### ###");
}

我們不想寫Int32? Int64? 和這個方法的其他版本,所以我們想重構它來處理泛型類型參數:

public String FormatValue<T>(T item)
{
 if (item.HasValue==false) return ""; // ERROR: no .HasValue property
 return item.Value.ToString("### ### ###"); // ERROR: usually has no ToString() with string argument
}

我該如何處理這種情況? 我試圖使用"where T"條款,但沒有任何成功。

首先:

public String FormatValue<T>(Nullable<T> item)
     where T : struct, IFormattable
{
   if (item.HasValue==false) return ""; 
   return item.Value.ToString("### ### ###", null /* you format provider */ );
}

您將通用T作為參數傳遞,但您需要Nullable

其次: Nullable ToString()已經做了你需要的東西 - 你不必手動完成(這是以防萬一,你不需要格式化):

int? a = null;
Console.WriteLine(a.ToString()); // outputs "", no any exception

嘗試將方法的參數定義為Nullable<T>

public String FormatValue<T>(Nullable<T> item) where T : struct
{
    return item.HasValue ? item.Value.ToString("### ### ###") : String.Empty;
}

既然你只想要你的方法為可空類型,那么在使用T?似乎沒有問題T? 作為參數而不是T 然后,您可以約束T :它必須實現IFormattable ,基本整數類型實現它。

public string FormatValue<T>(T? item) where T : struct, IFormattable
{
  if (item == null) return "";
  return item.Value.ToString("### ### ###", null);
}

使用IFormattable可能是最好的主意,但您也可以使用string.Format

public string FormatValue<T>(T? item) where T : struct
{
  return string.Format("{0:### ### ###}", item);
}

暫無
暫無

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

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