gpt4 book ai didi

c# - 将可为空的数字转换为字符串

转载 作者:太空狗 更新时间:2023-10-29 21:05:53 26 4
gpt4 key购买 nike

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

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

还有更短的吗?

最佳答案

你可以写一些扩展方法:

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

使用会更简单:

string s = i.ToNullString();

或通用版本:

public static string ToNullString<T>(this Nullable<T> value)
where T : struct
{
if (value == null)
return null;

return value.ToString();
}

关于c# - 将可为空的数字转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11472183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com