重载的ToString() [英] override .ToString()

查看:151
本文介绍了重载的ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重写的ToString()函数,以便每当我得到一个双
它小数点后只能输出5位。



我如何reffer到的ToString正在对象,覆盖功能里面呢?
在什么shell我把代替XXX的在下面的代码换句话说?



 公共重写字符串的ToString() 
{
如果(XXX.GetType()==名双)。
回报率(Math.Round(XXX,5));
}


解决方案

为什么不直接使用内置-in格式

  VAR PI =3.14159265米?; 
Console.WriteLine(pi.ToString(N5));
- > 3.14159

有关引用我喜欢的。NET格式字符串快速参考由约翰·希恩的。


I would like to override the .ToString() function so that whenever I get a double it outputs only 5 digits after the decimal point.

How do I reffer to the object the .ToString is working on, inside the override function? In other words what shell I put instead of the XXX in the following code?

public override string ToString()
{
    if (XXX.GetType().Name == "Double")
        return (Math.Round(XXX, 5));
}

解决方案

Why not just use the built-in formatting?

var pi = 3.14159265m;
Console.WriteLine(pi.ToString("N5"));
-> "3.14159"

For reference I like the .NET Format String Quick Reference by John Sheehan.

这篇关于重载的ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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