公共重写字符串ToString()? [英] public override string ToString()?
本文介绍了公共重写字符串ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
namespace CSharp_Accessors
{
class Person
{
private string myName = "N/a"; // Private string, cannot be accessed directly:
private int myAge = 0; // Private Integer, cannot be accessed directly:
public string Name
{
get { return myName; } // This is an Accessor, is used to access private identifiers:
set { myName = value; } // In this case the private identifier is [myName]:
}
public int Age
{
get { return myAge; } // This is an Accessor, is used to access private identifiers:
set { myAge = value; } // In this case the private identifier is [myAge]:
}
public override string ToString() //
{ // I dont understand how this is access or why this function is read without nay name given to it.
return "Name = " + Name + ", Age = " + Age; //
}
static void Main(string[] args)
{
Console.WriteLine("Simple Properties");
// Create a new Person object:
Person Person = new Person();
// Print out the name and the age associated with the person:
Console.WriteLine("Person details - {0}", Person);
// Set some values on the person object:
Person.Name = "Joe Beef";
Person.Age = 42;
Console.WriteLine("Person details - {0}", Person);
// Increment the Age property:
Person.Age += 1;
Console.WriteLine("Person details - {0}", Person);
// Pause screen
Console.ReadKey();
}
}
}
我不明白当该块没有名称关联或未调用时如何调用该块.
---
I dont understand how this block called when it doesnt have a name associated with it nor has it been called.
---
public override string ToString() //
{ // I dont understand how this is access or why this function is read without nay name given to it.
return "Name = " + Name + ", Age = " + Age; //
}
---
我正在阅读位于以下位置的教程:
属性或访问器
---
I was reading the tutorial found at:
Properties or Accessors
推荐答案
Console.WriteLine("Person details - {0}", Person);
使用ToString()
方法.
当您重写此方法时(如您在类中所做的那样),将调用此重写方法.
如果没有,则将调用默认的ToString
方法.
如何:覆盖ToString方法 [ ^ ]可能会给您有关此问题的更多见解.
Console.WriteLine("Person details - {0}", Person);
uses theToString()
method.
When you override this (as is done in your class), this overriden method is called.
If not, the defaultToString
method would have been called.
How To: Override the ToString Method [^] might give you some more insight into this issue.
这篇关于公共重写字符串ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文