hashtable中存结构,并存成文件,然后从文件读出,打印结构数据

我看你有戏 2010-11-17 12:04:19
如题
...全文
72 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
兔子-顾问 2010-11-17
  • 打赏
  • 举报
回复
可能是因为hashtable中存储的是object,无法确定每个结构一致,你考虑ToArray后再序列化,或是考虑用泛型版本的字典Dictionary<Key,Value>
我看你有戏 2010-11-17
  • 打赏
  • 举报
回复
我发现,存结构序列化后,恢复不了
我看你有戏 2010-11-17
  • 打赏
  • 举报
回复
大哥帮帮忙
我看你有戏 2010-11-17
  • 打赏
  • 举报
回复
大哥数据多了好像就会有问题
福来哥 2010-11-17
  • 打赏
  • 举报
回复
测试了一下,完全可以的啊!


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;

namespace HashTable序列化结构
{
[Serializable]
struct MyStruct
{
public int a;
public string b;

public MyStruct(int a,string b)
{
this.a = a;
this.b = b;
}
}

class Program
{
static void Main(string[] args)
{
MyStruct sct = new MyStruct(10, "abc");
Hashtable table = new Hashtable();
table.Add("test", sct);

Console.WriteLine("正在序列化");
FileStream fs = new FileStream("temp.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, table);
fs.Close();

Console.WriteLine("正在反序列化");
FileStream fs2 = new FileStream("temp.bin", FileMode.Open);
Hashtable table2 = bf.Deserialize(fs2) as Hashtable;
fs2.Close();

MyStruct sct2 = (MyStruct)table2["test"];
Console.WriteLine(sct2.a);
Console.WriteLine(sct2.b);

Console.ReadLine();
}
}
}

110,534

社区成员

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

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

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