ASP.NET:使用自定义类型为值的哈希表进行序列化和反序列化
创始人
2024-09-20 00:30:22
0

在ASP.NET中使用自定义类型作为哈希表的值时,需要将其序列化和反序列化以便在不同的应用程序之间传输和存储数据。以下是一个示例:

定义自定义类型:

public class Person { public string FullName { get; set; } public int Age { get; set; } }

创建哈希表:

Hashtable ht = new Hashtable(); ht.Add("John", new Person { FullName = "John Smith", Age = 25 }); ht.Add("Mary", new Person { FullName = "Mary Johnson", Age = 30 }); ht.Add("Bob", new Person { FullName = "Bob Williams", Age = 40 });

使用BinaryFormatter进行序列化:

using System.IO; using System.Runtime.Serialization.Formatters.Binary;

MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, ht); byte[] serializedData = stream.ToArray();

使用BinaryFormatter进行反序列化:

MemoryStream stream = new MemoryStream(serializedData); BinaryFormatter formatter = new BinaryFormatter(); Hashtable deserializedHT = (Hashtable)formatter.Deserialize(stream);

foreach (DictionaryEntry entry in deserializedHT) { string key = (string)entry.Key; Person value = (Person)entry.Value; Console.WriteLine("{0}: {1}, {2} years old", key, value.FullName, value.Age); }

注意:使用BinaryFormatter进行序列化和反序列化会将对象转换为二进制,并可能不适用于所有情况,因此建议使用其他序列化方法,如JSON或XML。

相关内容

热门资讯

透视美元局!aapoker插件... 透视美元局!aapoker插件(透视)发牌逻辑(一贯存在有挂);1、游戏颠覆性的策略玩法,独创攻略技...
透视安卓版!aapoker怎么... 透视安卓版!aapoker怎么设置提高好牌几率(透视)ai插件(一贯存在有挂)1)aapoker怎么...
透视黑科技!aapoker怎么... 透视黑科技!aapoker怎么提高中牌率(透视)ai插件(好像真的有挂);1、完成aapoker怎么...
透视存在!aapoker怎么提... 透视存在!aapoker怎么提高中牌率(透视)发牌逻辑(切实真的是有挂)小薇(透视辅助)致您一封信;...
透视规律!aapoker俱乐部... 透视规律!aapoker俱乐部靠谱吗(透视)脚本(真是存在有挂)1、透视规律!aapoker俱乐部靠...
透视代打!aapoker怎么选... 透视代打!aapoker怎么选牌(透视)万能辅助器(都是真的是有挂)一、aapoker怎么选牌AI软...
透视模拟器!aapoker怎么... 透视模拟器!aapoker怎么拿好牌(透视)免费透视脚本(果然真的有挂)1、操作简单,无需注册,只需...
透视有挂!aapoker辅助插... 透视有挂!aapoker辅助插件工具(透视)透视脚本(竟然存在有挂);1、下载好aapoker辅助插...
透视肯定!aapoker脚本怎... 透视肯定!aapoker脚本怎么用(透视)插件下载(竟然有挂)aapoker脚本怎么用辅助器中分为三...
透视中牌率!aapoker辅助... 透视中牌率!aapoker辅助器怎么用(透视)透视软件(确实有挂)运aapoker辅助器怎么用辅助工...