简体   繁体   English

覆盖.ToString()

[英]override .ToString()

I would like to override the .ToString() function so that whenever I get a double it outputs only 5 digits after the decimal point. 我想覆盖.ToString()函数,这样每当我得到一个double时,它只输出小数点后的5位数。

How do I reffer to the object the .ToString is working on, inside the override function? 如何在覆盖函数内部对.ToString正在处理的对象进行处理? In other words what shell I put instead of the XXX in the following code? 换句话说,我在下面的代码中放了什么shell而不是XXX?

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. 作为参考,我喜欢John Sheehan的.NET Format String Quick Reference

You can't override a method for a different type - basically you can't stop double.ToString doing what it does. 你不能覆盖不同类型的方法 - 基本上你不能停止double.ToString做它做的事情。 You can, however, write a method which takes a double and formats it appropriately. 但是,您可以编写一个方法,该方法采用double并对其进行适当格式化。

As Jon pointed out, you can't override Double.ToString . 正如Jon指出的那样,你无法覆盖Double.ToString You can create an extension method for double type that helps you do this: 您可以为double类型创建一个扩展方法,以帮助您执行此操作:

public static class DoubleExtensions {
   public static string ToStringWith5Digits(this double x) { ... }
}

and use it like: 并使用它像:

double d = 10;
string x = d.ToStringWith5Digits(); 

You can pass a format argument to Double.ToString() specifying the number of digits: 您可以将格式参数传递给Double.ToString()指定位数:

double x = 5.12345667;
string s = x.ToString("F5"); // s="5.12345", x.ToString("#.#####") also works

You can't override the ToString() function for doubles (it is a member function of struct Double) 你不能覆盖双精度的ToString()函数(它是struct Double的成员函数)

What class does your ToString() function belong to? 你的ToString()函数属于哪个类? Typically you have private variable inside the class you use. 通常,您使用的类中包含私有变量。 (But could also be a combination of variables to build a ToString()) (但也可以是构建ToString()的变量组合)

eg: (pseudo code this is) 例如:(这是伪代码)

class MyClass
{
  private double dd;
  private string prefix = "MyDouble:";
  ...
  ...
    public override string ToString()
    {
        if (dd.GetType().Name == "Double")
        return ( prefix + Math.Round(dd, 5).ToString() );
    }
}

you cannot override, but you could a extension method 你不能覆盖,但你可以扩展方法

public static string ToRoundString(this double doubleValue)
{
   return Math.Round(doubleValue, 5).ToString();
}

usage 用法

public void TestMethod()
{
   double greatValue = 3;
   string newString = greatVale.ToRoundString();
}

cheers 干杯

While the "F5" or "#.#####" solves the specifics of the original post, as the title is rather broader ("override .ToString()"), I thought I'd add that you can also create an extension method which overloads ToString() . 虽然“F5”或“#。#####”解决了原帖的细节,因为标题相当广泛(“覆盖.ToString()”),我想我会补充说你也可以创建一个重载ToString()的扩展方法。

So, for example, an extension method of: 因此,例如,扩展方法:

    public static string ToString(this double value, int roundTo, string roundSuffix)
    {
        string rounded = value.ToString($"#.{new String('#', roundTo)}");
        if (rounded != value.ToString())
        {
            rounded = $"{rounded}{roundSuffix}";
        }
        return rounded;
    }

Would produce "5.25 was rounded" if passed 如果通过将产生“5.25四舍五入”

double d = 5.2514;
string formatted = d.ToString(2, " was rounded");

or "5.2" if passed 或“5.2”如果通过

double d = 5.2;
string formatted = d.ToString(2, " was rounded");

(just on the off chance there's some weird use case where someone wants to do something like that!) (只是在关闭机会有一些奇怪的用例,有人想做那样的事情!)

You shouldn't attempt to override ToString() with a method that has the same signature as one of the built-in ToString() overloads however, as while the IDE will see it, it will never call the extension method (see How to call extension method which has the same name as an existing method? for details) 您不应该尝试使用与内置ToString()重载之一具有相同签名的方法来覆盖ToString() ,但是,当IDE将看到它时,它将永远不会调用扩展方法(请参阅如何与现有方法同名的呼叫扩展方法?详情)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM