如何在类中重写和格式化 ToString() 方法?

发布于 2024-11-01 04:27:47 字数 177 浏览 0 评论 0原文

我搜索了谷歌和这个网站来找到答案。我在课本上也看过,但还是不明白它是如何应用的。

这是我所知道的:

  • 它用于显示对象对自身的了解。

  • 它可用于格式化有关其自身了解的输出。

  • 它必须在要使用的方法中被重写。

I have searched both Google and this site to find an answer. I have also read it in my class book, but I still don't understand how it is applied.

Here is what I know:

  • It is used to display what an object knows about itself.

  • It can be used to format the output about what it knows about itself.

  • It has be be overridden in the method to be used.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

枯寂 2024-11-08 04:27:47

认为你有一个像这样的类:

public class Person
{
   public string FirstName { get; set;}
   public string LastName { get; set;}
   private string age;
}

使用这个:

public override string ToString()
{
   return string.Format("[First Name: {0}; Last Name: {1}; Age: {2}]", FirstName, LastName, age);
}

将揭示该类的所有内部结构。实际上,它最适合以预先格式化的方式快速检索类的公共字段(从而有效地将类中封装的数据转换为字符串)。

另外,这里还有《Pro C# 2010 and the .NET 4 Platform》一书中的非常有用的建议:“您创建的许多类(和结构)可以受益于重写 ToString() 以返回字符串类型当前状态的文本表示对于调试来说非常有帮助(除其他原因外),您选择如何构造此字符串是个人选择的问题;但是,建议的方法是将每个名称/值对分开。但是,请始终记住,当您为扩展自定义基类的类重写 ToString() 时,正确的 ToString() 重写还应该考虑继承链上定义的任何数据。第一个任务是使用 base 关键字从父类获取 ToString() 值。获得父类的字符串数据后,您可以附加派生类的自定义信息。”

Thinking that you have a class like:

public class Person
{
   public string FirstName { get; set;}
   public string LastName { get; set;}
   private string age;
}

Using this:

public override string ToString()
{
   return string.Format("[First Name: {0}; Last Name: {1}; Age: {2}]", FirstName, LastName, age);
}

will reveal all the internals of the class. Actually it is best used for quickly retrieving public fields of the class in a pre-formatted manner (thus effectively converting the data encapsulated in the class into a string).

Also here is a very useful advice from the book Pro C# 2010 and the .NET 4 Platform: "Many classes (and structures) that you create can benefit from overriding ToString() in order to return a string textual representation of the type’s current state. This can be quite helpful for purposes of debugging (among other reasons). How you choose to construct this string is a matter of personal choice; however, a recommended approach is to separate each name/value pair with semicolons and wrap the entire string within square brackets. However, always remember that a proper ToString() override should also account for any data defined up the chain of inheritance. When you override ToString() for a class extending a custom base class, the first order of business is to obtain the ToString() value from your parent using the base keyword. Once you have obtained your parent’s string data, you can append the derived class’s custom information."

绾颜 2024-11-08 04:27:47

所有 .NET 类的基类都是 object 类型。对象类为您提供了 ToString() 的默认实现,默认情况下仅打印出类的名称,除非该类已重写了 ToString() 方法以打印其他东西。类的名称并不是特别有用,因此在您编写的任何类中重写 ToString() 通常是一个好习惯,因为它对于提供类的人类可读表示很有用。当您想要检查类的实例时,调试器实际上会默认使用您的 ToString() 实现。

在您的类中,您所要做的就是添加此方法:

public override string ToString()
{
    // return a string that has something to do with your class
}

示例:

public class Person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int Age {get;set;}

    public override void ToString()
    {
        // return whatever makes sense here...
        return string.Format("[Person: FirstName={0}, LastName={1}, Age={2}]", FirstName, LastName, Age);
    }
}

请注意 string.Format 方法只是创建字符串的一种方法。 string.Format 的第一个参数是“格式”,它可以包含文字文本以及您将作为其他参数提供的值的占位符。上面的 {0}{1}{2} 是 FirstName、LastName 和 Age 参数的占位符,这些参数在之后传递格式。如果你想了解更多。

The base class for all .NET classes is the object type. The object class provides you with a default implementation of ToString() which by default just prints out the name of the class, unless the class has overridden the ToString() method to print something else. The name of the class is not particularly useful, so it's usually a good practice to override ToString() in any class you write, because it's useful to provide a human-readable representation of your class. The debugger will actually use your ToString() implementation by default when you want to inspect an instance of your class.

In your class, all you have to do is add this method:

public override string ToString()
{
    // return a string that has something to do with your class
}

Example:

public class Person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int Age {get;set;}

    public override void ToString()
    {
        // return whatever makes sense here...
        return string.Format("[Person: FirstName={0}, LastName={1}, Age={2}]", FirstName, LastName, Age);
    }
}

Note the string.Format method is just a way of creating a string. The first argument to string.Format is the "format," which can contain literal text as well as placeholders for values that you will provide as the other arguments. The {0}, {1}, and {2} above are placeholders for the FirstName, LastName, and Age arguments which are passed after the format. I would read up on string.Format if you want to know more.

贪恋 2024-11-08 04:27:47

重写 ToString() 方法:

public class Test
{
   public string FirstName { get; set; }

   public string LastName { get; set; }

   public override string ToString()
   {
      // Do your formatting here
      return LastName + ", " + FirstName;
   }
}

Override ToString() method:

public class Test
{
   public string FirstName { get; set; }

   public string LastName { get; set; }

   public override string ToString()
   {
      // Do your formatting here
      return LastName + ", " + FirstName;
   }
}
断桥再见 2024-11-08 04:27:47

您必须在类中重写 ToString() 。假设我有一堂包含 m_nDays、m_nHours、m_nMinutes... 的课程,那么我可以重写 ToString(),如下所示:

public override string ToString()
{
    return string.Format("{0,5}d - {1:00}:{2:00}", m_nDays, m_nHours, m_nMinutes);
}

You have to override ToString() in your class. Say I have a class with m_nDays, m_nHours, m_nMinutes... then I could override ToString() as follows:

public override string ToString()
{
    return string.Format("{0,5}d - {1:00}:{2:00}", m_nDays, m_nHours, m_nMinutes);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文