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

Sou*_*han 3 c# serialization dictionary binary-serialization

我在C#中有一本字典

private Dictionary<int, UserSessionInfo> userSessionLookupTable = new Dictionary<int, UserSessionInfo>();
Run Code Online (Sandbox Code Playgroud)

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

this.userSessionLookupTable.Add(userSessionInfoLogin.SessionId, userSessionInfoLogin);
Run Code Online (Sandbox Code Playgroud)

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

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

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

谁可以帮我这个事??

Mon*_*nty 6

尝试这个....

    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));
    }
Run Code Online (Sandbox Code Playgroud)

用法...

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

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