C#中的一处为什么用toString呢

来源:百度知道 编辑:UC知道 时间:2024/06/01 08:44:00
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DEMO16
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Person obj = new Person();
obj[0] ="大家好";
textBox1.Text=(obj.temp[1]).ToString();
}
public class Person
{
public string temp = "";
public string this[int index]
{
get { return temp; }
set { temp = value; }
}
}

}

}
这句话textBox1.Text=(obj.temp[1]).ToString(); 中为啥用ToString?“大家好”不就是字符串型的吗?

Person obj = new Person();
obj[0] ="大家好";

new Person(); 有个 new 字,说明 obj 是一个引用类型,不是值类型,所以就转换下。引用类型没办法直接输出。

string temp

temp[i]是char类型的。所以要用ToString转成String型。

你运行下就知道了,输出的是“家”而不是“大家好”,tostring()是将char转为string。

此处把temp字符串看成char型数组
(字符串可以看做char型只读数组)
所以temp[1]是char型的,要用toString
转换为字符串型的。

你的obj.temp[1]本身就是string类型,不需要tostring
把一个非string类型变量赋值给一个string类型变量的时候才需要ToString()

文本框只接收字符串型,那么对于其他类型的只有转换成字符串类型赋给文本框