c# - 为类中的 int 元素覆盖 ToString()

标签 c# .net

我想重写 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/

相关文章:

c# - .NET 中的点有多贵?

c# - 如何覆盖单个自动映射器属性映射?

c# - 在 .Net 中使用 dbContext 后连接保持打开状态

c# - 我的 Windows 窗体项目上的 Media Player 经典库

.net - NUnit 测试在 OpenCover 中失败

c# - 在 Windows x64 中从句柄获取可执行文件名

C# XNA - 读取 .txt 文件并创建二维数组

c# - NHibernate Order By 问题

c# - 当 SetCompatibleTextRenderingDefault 抛出 InvalidOperationException 时,如何找出已创建的 IWin32Window?

c# - 从 IEnumerable<T> 到 MyCollection 的隐式转换