ToString了解 [英] ToString Understanding

查看:83
本文介绍了ToString了解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习编程,并想知道粗体部分是什么以及它做了什么

 

class
{
public string 名称{ get ; set ; }
public int 年龄{ get ; set ; }

public < span class ="x_x_hljs-keyword"style ="color:#0101fd"> 覆盖 字符串 ToString ()
{
返回 " Person:" + Name + " " +年龄;
}

}

Person person = new Person {Name = " John" ,年龄= 12 };
Console.WriteLine(person);
//输出:
// Person:John 12

解决方案

是的,有很多误解那个方法。 


这是一个来自.Net的基类对象的方法(因此可以在其他所有类中使用)


主要是它被覆盖以返回表示 


在值类型(结构)中,这是标准的完成。 


如果它没有覆盖ToString返回类姓名。 


所以在你的班级中发生的事情是,如果已经完成 


person.ToString()则会返回Person:John 12


I recently started learning programming and was wondering what the bolded portion is and what it does

class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return "Person: " + Name + " " + Age; }

}

Person person = new Person { Name = "John", Age = 12 }; Console.WriteLine(person); // Output: // Person: John 12

解决方案

Yes there are much misunderstanding about that method. 

It is a method from the base Class Objects of .Net (and therefore available in every other class)

Mostly it is overridden to return representations 

In Value types (structures) this is standard done. 

If it is not overriden ToString returns the class name. 

So what happens in your class is that if is done 

person.ToString() there is returned Person: John 12


这篇关于ToString了解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆