C# 输入输出流的问题

cg173619268 2009-09-05 11:31:27
我先把一个对象写入一个一.sav的文件里。然后当我再次运行程序的时候在吧这对象直接读出来。
比如说我写了个 public class Man{
String name;
String sex;
public Man()
{

}
public Man(String name,String sex)
{
this.name=name;
this.sex=sex;
}
public void static main(String[] args)
{
Man man1=new Man("张三","男");
//然后将这个对象写入一个.sav的文件
......
//然后将他读出来
}

}

请高手帮我解决下,我用的StreamReader这个类 的方法 读出来只返回String 类型。
有没想JAVA那样直接读出来是对象?
高手帮忙解决下
...全文
230 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
LMTZ 2009-09-08
  • 打赏
  • 举报
回复
using System.Runtime.Serialization;
using System.IO;

[Serializable]
public class Man{
String name;
String sex;
public Man()
{
}
public Man(String name,String sex)
{
this.name=name;
this.sex=sex;
}
public void static main(String[] args)
{
Man man1=new Man("张三","男");
XmlSerializer xmls = new XmlSerializer(typeof(Man));
//然后将这个对象写入一个.sav的文件
using (Stream s = new FileStream("file.sav", FileMode.Create))
{
xmls.Serialize(s, man1);
}
//然后将他读出来
Man man2 = null;
using (Stream s = new FileStream("file.sav",FileMode.Open))
{
man2 = (Man)xmls.Deserialize(s, man1);
}
}
}
hangang7403 2009-09-08
  • 打赏
  • 举报
回复
9楼的兄弟你的思路是对的,就是错误太多了,改正如下:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Serialization ;
[Serializable()]
public class Man
{
string name;
string sex;
public Man()
{
}
public Man(string name,string sex)
{
this.name=name;
this.sex=sex;
}
public static void Main(string[] args)
{
Man man1=new Man("张三","男");
XmlSerializer xmls = new XmlSerializer(typeof(Man));
//然后将这个对象写入一个.sav的文件
using (Stream s = new FileStream("file.sav", FileMode.Create))
{
xmls.Serialize(s, man1);
}
//然后将他读出来
Man man2 = null;
using (Stream s = new FileStream("file.sav",FileMode.Open))
{
man2 = (Man)xmls.Deserialize(s);
}
}
}
cg173619268 2009-09-07
  • 打赏
  • 举报
回复
高手举个例子,实在用不了。
LMTZ 2009-09-06
  • 打赏
  • 举报
回复
使用序列化。
序列化机制将类的值转换为一个的连续的字节流,然后就可以将这个流写到磁盘文件或其他流化目标上。

如果楼主需要自定义序列化,可以在对象上实现ISerializable, 实现自定义数据组织方式。
FlyinFish 2009-09-06
  • 打赏
  • 举报
回复
继承ISerializable Interface可以让你的自定义类变成可以序列化的。

http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.iserializable.aspx
flyxiaoyao 2009-09-05
  • 打赏
  • 举报
回复
参考MSDN中 SerializableAttribute 类 ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/fxref_mscorlib/html/7daddf30-215f-afb9-3b3e-d6dcbdb28915.htm

里面有demo
cg173619268 2009-09-05
  • 打赏
  • 举报
回复
没懂 我知道JAVA 写对象必须继承一个类 这个类就可以序列化
但是C#中怎么来弄 弄点代码上来(加注释谢谢了)
dancingbit 2009-09-05
  • 打赏
  • 举报
回复
该死的CSDN...

注意对象必须是可序列化的。
dancingbit 2009-09-05
  • 打赏
  • 举报
回复
使用BinaryFormatter的Serialize方法和Deserialize方法将对象序列化和反序列化。
dancingbit 2009-09-05
  • 打赏
  • 举报
回复
使用BinaryFormatter的Serialize方法和Deserialize方法将对象序列化和反序列化。

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧