c# - 在 C# 中保存 Dictionary<int, object> - 序列化?

标签 c# dictionary serialization binary-serialization

我有一个 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/

相关文章:

c# - 持续从流​​中读取?

c# - DropDownList 选定值在 POST 操作的模型中设置为 "null"

Python - 将多个 Pickle 对象加载到一个字典中

python - 解构绑定(bind)字典内容

python - 循环添加记录到字典中

.net - RestSharp for JSON 中的属性映射不起作用

serialization - protobuf 消息的分隔符是什么?

c# - 编译器是否优化对 const 变量和文字 const 数字的操作?

c# - 我如何解决这个 lambda 表达式外部变量问题?

regex - 在 R 语料库中搜索以 "esque"结尾的所有单词