可空转换成数字串 [英] Convert nullable numeric into string

查看:123
本文介绍了可空转换成数字串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要一个不能为空的数字转换成一个字符串的维护的空值。这是我在做什么:

I want to convert a nullable numeric into a string maintaining the null value. This is what I'm doing:

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



是不是有什么短?

Is there something shorter?

推荐答案

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

You could create an extension method for that:

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



用法:

Usage:

var s = i.ToStringOrNull();

这篇关于可空转换成数字串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆