简体   繁体   English

如何在C#中覆盖ToString()方法?

[英]How can I override the ToString() method in C#?

I want to override the Tostring() method for changing some characters. 我想覆盖Tostring()方法来改变一些字符。 Is it possible? 可能吗? If yes, How can I do this? 如果是,我该怎么做?

In your class where you want to override it in, add: 在您要在其中覆盖它的类中,添加:

public override string ToString()
{
  // return your string representation
}

As per your question, to change some characters in the ToString implementation, you need to call the existing ToString method by using the base keyword: 根据您的问题,要更改 ToString实现中的某些字符,您需要使用base关键字调用现有的ToString方法:

public override string ToString()
{
    return base.ToString().Replace("something", "another thing");
}

Note that if you forget the base keyword it will call itself repeatedly until you get a StackOverflowException . 请注意,如果您忘记了base关键字,它将重复调用自身,直到您获得StackOverflowException

Add the following in the class you want to override the ToString function: 在要覆盖ToString函数的类中添加以下内容:

public override string ToString()
{
    // Add your implementation here
}

See example at MSDN . 请参阅MSDN上的示例。

public override String ToString() 
{
    return String.Format("Test {0}", 101);
}

All you need is to try to write public override , and then Visual Studio will create the method for you like this: 您只需要尝试编写公共覆盖 ,然后Visual Studio将为您创建这样的方法:

 public override string ToString()
 {
      // Implement your own code and return desired string
 }

If someone looks for a general answer to "How to override the ToString() method", I've written a post, " Override ToString() using JSON serialization or something else ." 如果有人寻找“如何覆盖ToString()方法”的一般答案,我写了一篇帖子,“ 使用JSON序列化或其他东西覆盖ToString() 。”

In a summary, the following technologies can be used to simplify creation of ToString(): 总结一下,以下技术可用于简化ToString()的创建:

  1. JSON serialization (either DataContractJsonSerializer, JSON.NET or the NuGet package JsonValue). JSON序列化(DataContractJsonSerializer,JSON.NET或NuGet包JsonValue)。

  2. XmlSerialize XMLSERIALIZE

  3. LINQPad's dump an arbitrary object to an HTML string LINQPad 将任意对象转储到HTML字符串

  4. ServiceStack.Text C# .NET Extension method: T.Dump(); ServiceStack.Text C#.NET扩展方法:T.Dump();

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

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