覆盖 .ToString 方法 c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18200427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Override .ToString method c#
提问by Zoro
Okay, so I wrote this program out of the exercise of a C# programming book (I'm trying to learn here) and it asks for "Override the ToString() method to return all data members".
好的,所以我根据一本 C# 编程书的练习编写了这个程序(我正在尝试在这里学习),它要求“覆盖 ToString() 方法以返回所有数据成员”。
Have I done this correctly? Or have I just successfully wrote code that compiles but does nothing. What is the purpose of ToString?
我做对了吗?或者我刚刚成功编写了可以编译但什么都不做的代码。ToString的目的是什么?
I have spent about 30 minutes looking at other posts on this and havn't figured it out, So I decided to make this.
我花了大约 30 分钟查看有关此的其他帖子,但还没有弄清楚,所以我决定做这个。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication297
{
class Program
{
static void Main(string[] args)
{
String name = "Stormtrooper";
Employee s = new Employee(name);
Console.WriteLine("The type of hire is a {0}", s.Name);
Console.WriteLine("The identification number is {0}", s.Number);
Console.WriteLine("The date of hire is {0} ABY", s.Date);
Console.WriteLine("The standard galactic salary is...{0:C}", s.Salary);
}
class Employee
{
private string _name;
private string _number;
private int _date;
private int _salary;
public string Name
{
get
{
return _name;
}
}
public string Number
{
get
{
return _number;
}
}
public int Date
{
get
{
return _date;
}
}
public int Salary
{
get
{
return _salary;
}
}
public Employee(string n)
{
_name = n;
_number = "AA23TK421";
_date = 4;
_salary = 800;
}
}
public override string ToString()
{
return "_name + _number + _date + _salary".ToString();
}
}
}
采纳答案by Scott Chamberlain
You are returning a string that just says the phrase _name + _number + _date + _salary
.
您正在返回一个只显示短语的字符串_name + _number + _date + _salary
。
What you likely wanted to do is build a string using those fields. If you wanted them all mushed together Concatwould work, but it would be highly un-readable
您可能想要做的是使用这些字段构建一个字符串。如果您希望将它们全部混合在一起,则Concat可以工作,但会非常不可读
public override string ToString()
{
return String.Concat(_name, _number, _date, _salary);
}
However what would be better is to use Formatand include labels with the values
但是,更好的是使用Format并包含带有值的标签
public override string ToString()
{
return String.Format("Name:{0}, Number:{1}, Date:{2}, Salary:{3}",_name, _number, _date, _salary);
}
If you are using C# 6 or newer you can use the following cleaner format
如果您使用的是 C# 6 或更新版本,您可以使用以下更简洁的格式
public override string ToString()
{
return $"Name:{_name}, Number:{_number}, Date:{_date}, Salary:{_salary}";
}
Which is the exact same logic as the previous String.Format
version.
这与以前的String.Format
版本完全相同的逻辑。
回答by Adriaan Stander
Rather try something like
而是尝试类似的东西
public override string ToString()
{
return String.Format("Name : {0}, number {1}, date {2}, salary {3}",_name,_number,_date,_salary);
}
But it neads to be part of the class
但它需要成为课堂的一部分
so
所以
class Employee
{
private string _name;
private string _number;
private int _date;
private int _salary;
.....
public override string ToString()
{
return String.Format("Name : {0}, number {1}, date {2}, salary {3}",_name,_number,_date,_salary);
}
}
Have a look at String.Format Method
Replaces each format item in a specified string with the text equivalent of a corresponding object's value.
用对应对象值的文本替换指定字符串中的每个格式项。
回答by Rex
You could try to format the output in a nice format. (not tested, though)
您可以尝试以良好的格式格式化输出。(虽然没有测试)
public override string ToString()
{
return string.Format("Name: {0} Number: {1:n0} Date: {2:yyyy-MM-dd} Salary: {3:n2}", _name, _number, _date, _salary);
}
there are a lot of purposes overwriting .ToString(), depending on the context. for example,
根据上下文,有很多目的可以覆盖 .ToString()。例如,
- some developers like to have nicely formatted object description when doing debug, overwriting .ToString() would allow them to have meaningful description with some identifier (for example, the Id of a object);
- Some developers like to put some serialization code into the ToString() method;
- Some developers even put some debug code into the .ToString() method, though it might not be a good practice.
- 一些开发人员喜欢在调试时使用格式良好的对象描述,覆盖 .ToString() 将允许他们使用某些标识符(例如,对象的 Id)进行有意义的描述;
- 有些开发者喜欢在 ToString() 方法中放入一些序列化代码;
- 一些开发人员甚至将一些调试代码放入 .ToString() 方法中,尽管这可能不是一个好的做法。
it really depending on the context of your needs. you may find some good practices to follow online - believe there are plenty of resources online.
这真的取决于您的需求。您可能会在网上找到一些好的做法 - 相信网上有很多资源。
回答by Karl Anderson
The reason people override the ToString()
method is to have a default string representation of your object, usually for display to the user or in a log or console, like this:
人们重写该ToString()
方法的原因是拥有对象的默认字符串表示形式,通常用于显示给用户或在日志或控制台中,如下所示:
Console.WriteLine(yourClassObject);
If you do not override the ToString()
, then its default implementation is to return the fully qualified name of your object, like this:
如果不覆盖ToString()
,则其默认实现是返回对象的完全限定名称,如下所示:
YourNamespace.YourClassName
By changing the inherited implementation (from System.Object
), then you can make a nicer (read: prettier) representation, like this:
通过更改继承的实现(来自System.Object
),您可以制作更好(阅读:更漂亮)的表示,如下所示:
public override string ToString()
{
return String.Format("This instance of my object has the following: Name = {0}, Number = {1}, Date = {2}, Salary = ", _name, _number, _date, _salary);
}
回答by bytedev
If you are using C# 6 (or later) use the nameof()
method for the property names in the string in case the propery names change. You can also use the $""
notation instead of using string.Format().
如果您使用的是 C# 6(或更高版本),请使用nameof()
字符串中的属性名称的方法,以防属性名称更改。您也可以使用$""
符号代替 string.Format()。
For example:
例如:
public override string ToString()
{
return $"{nameof(Name)}: {_name}";
}
回答by Guy
Without overiding ToString, if you tried to "get" the string value of an Employee, e.g.
在不覆盖 ToString 的情况下,如果您尝试“获取”员工的字符串值,例如
var employee1= new Employee();
Console.WriteLine(employee1);
var employee1= new Employee();
Console.WriteLine(employee1);
What you'd get is:
你会得到的是:
ConsoleApplication1.Program+Employee
ConsoleApplication1.Program+Employee
Which provides no information at all to help you (or a UI) display relevant information.
它根本不提供任何信息来帮助您(或 UI)显示相关信息。
I use
return _name + _number + _date + _salary;
Which defaults to string,
我使用
return _name + _number + _date + _salary;
默认为字符串,
or a more verbose
或更详细的
return "Name:" + _name + " Number:" + _number + " etc...";
return "Name:" + _name + " Number:" + _number + " etc...";
回答by MD Rakibuz Sultan
class Program
{
static void Main( )
{
int Number = 10;
Console.WriteLine(Number.ToString());
Customer cc = new Customer();
cc.FirstName = "Rakibuz";
cc.LastName = "Sultan";
Console.WriteLine(Convert.ToString(cc));
}
}
public class Customer
{
public string FirstName;
public string LastName;
public override string ToString()
{
return FirstName + " " + LastName;
}
}