是的,如果您首先将其序列化为 JSON 或 XML,则将其作为字符串...或者最简单的方法...ToString()
在您的类中添加一个方法:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person (string name, int age) {
this.Name = name;
this.Age = age;
}
public override string ToString()
{
return "Person: " + Name + " " + Age;
}
}
然后编写您的 Class 实例以将其写入文件:
private void btnSaveFile_Click(object sender, EventArgs e)
{
string mydocpath = ""; // add your path here
Person newPerson = new Person ("David", 32);
using (StreamWriter studentInfo = new StreamWriter(mydocpath + @"\Student.txt")) {
studentInfo.WriteLine(newPerson.ToString());
}
}
希望这可以帮助