gpt4 book ai didi

c# - 在 C# 中保存 Dictionary - 序列化?

转载 作者:行者123 更新时间:2023-11-30 13:36:18 26 4
gpt4 key购买 nike

我有一个 C# 字典

private Dictionary<int, UserSessionInfo> userSessionLookupTable = new Dictionary<int, UserSessionInfo>();

现在我已经创建了一个字典对象

this.userSessionLookupTable.Add(userSessionInfoLogin.SessionId, userSessionInfoLogin);

现在我想要一个通用方法来将字典序列化和反序列化为字节数组。喜欢

public static void Serialize(Dictionary<int, object> dictionary, Stream stream)
{
//Code here
}

public static static Dictionary<int, object> Deserialize(Stream stream)
{
//Code here
}

谁能帮我解决这个问题??

最佳答案

试试这个....

    public static void Serialize<Object>(Object dictionary, Stream stream)
{
try // try to serialize the collection to a file
{
using (stream)
{
// create BinaryFormatter
BinaryFormatter bin = new BinaryFormatter();
// serialize the collection (EmployeeList1) to file (stream)
bin.Serialize(stream, dictionary);
}
}
catch (IOException)
{
}
}

public static Object Deserialize<Object>(Stream stream) where Object : new()
{
Object ret = CreateInstance<Object>();
try
{
using (stream)
{
// create BinaryFormatter
BinaryFormatter bin = new BinaryFormatter();
// deserialize the collection (Employee) from file (stream)
ret = (Object)bin.Deserialize(stream);
}
}
catch (IOException)
{
}
return ret;
}
// function to create instance of T
public static Object CreateInstance<Object>() where Object : new()
{
return (Object)Activator.CreateInstance(typeof(Object));
}

用法...

        Serialize(userSessionLookupTable, File.Open("data.bin", FileMode.Create));
Dictionary<int, UserSessionInfo> deserializeObject = Deserialize<Dictionary<int, UserSessionInfo>>(File.Open("data.bin", FileMode.Open));

我在上面的代码中使用了“对象”来满足您的要求,但我个人会使用“T”,它通常表示 C# 中的通用对象

关于c# - 在 C# 中保存 Dictionary<int, object> - 序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com