我想重写 int 的 ToString()
方法(它是类的一部分),这样如果 int 的值为 0,则 ToString()
应该返回一个空字符串 ""
。这可以做到吗?
更新 只需创建一个
public string AmountToString {
get { if (Amount != 0) return Amount.ToString(); else return ""; }
}
我只是想看看它是否可以在原始类型上实现(ToString())
最佳答案
三种主要方法:
雇用 (custom) Format provider
所以你可以使用 i.ToString(formatprovider);
编辑 我想我找到了一个自定义格式字符串,它适用于默认的 .NET 数字格式提供程序:
i.ToString("0;-0;"); // works
从 The ";" Section Separator 上的页面提取的另一个示例:
i.ToString("##;(##);**Zero**"); // would return "**Zero** instead
Tip:
You can download the Format Utility, an application that enables you to apply format strings to either numeric or date and time values and displays the result string.
扩展方法
public static string ToStringOrEmpty(this int i)
{
return (0==i)? string.Empty : i.ToString();
}
访问助手:
class X
{
int member;
public string getMember() { return (0==member)? string.Empty : member.ToString();
}
关于c# - 为类中的 int 元素覆盖 ToString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8078705/