Csharp/C#教程:将可空数字转换为字符串分享


将可空数字转换为字符串

我想将可空数字转换为保持空值的字符串。 这就是我正在做的事情:

int? i = null; string s = i == null ? null : i.ToString(); 

有什么更短的东西吗?

您可以为此创建一个扩展方法:

 public static string ToStringOrNull(this Nullable nullable) where T : struct { return nullable.HasValue ? nullable.ToString() : null; } 

用法:

 var s = i.ToStringOrNull(); 

UPDATE

从C#6开始,您可以使用更方便的空条件运算符 :

 var s = i?.ToString(); 

你可以写一些扩展方法:

 public static string ToNullString(this int? i) { return i.HasValue ? i.ToString() : null; } 

用法会更简单:

 string s = i.ToNullString(); 

或通用版本:

 public static string ToNullString(this Nullable value) where T : struct { if (value == null) return null; return value.ToString(); } 

我认为

 string s = i?.ToString(); 

更短。

我需要formatProvider参数为十进制类型,所以删除通用版本专门为十进制扩展,如下所示:

上述就是C#学习教程:将可空数字转换为字符串分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public static string ToStringOrNull(this Nullable nullable, string format = null) { string resTmp = ""; if (nullable.HasValue) { if (format != null) { resTmp = nullable.Value.ToString(format); } else { resTmp = nullable.ToString(); } } else { resTmp = ""; } return resTmp; } 

www.ctvol.com true Article Csharp/C#教程:将可空数字转换为字符串分享

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/991313.html

(0)
上一篇 2021年12月23日 下午4:23
下一篇 2021年12月23日 下午4:23

精彩推荐