0

代码:

public static string Serialize<T>(IEnumerable<T> list)
{
    BinaryFormatter formatter = new BinaryFormatter();

    using (MemoryStream m = new MemoryStream())
    {
        formatter.Serialize(m, list);
        m.Position = 0;
        return Convert.ToBase64String(m.ToArray());
    } 

}

public static T Deserialize<T>(string listData)
{
    BinaryFormatter formatter = new BinaryFormatter();

    using (MemoryStream m = new MemoryStream())
    {
        return (IEnumerable<T>)formatter.Deserialize(m); //Problem is here
    }
}

错误:

Error   1   Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<T>' to 'T'. An
explicit conversion exists (are you missing a cast?)
4

2 回答 2

3

正如消息中明确指出的,您不能IEnumerable<T>从声明为返回的方法中返回一个T

于 2012-06-05T20:46:48.950 回答
1

将返回类型从 更改TIEnumerable<T>。您还需要用字符串填充内存流,例如:

public static IEnumerable<T> Deserialize<T>(string listData)
{
    BinaryFormatter formatter = new BinaryFormatter();

    using (MemoryStream m = new MemoryStream(Convert.FromBase64String(listData)))
    {
        return (IEnumerable<T>)formatter.Deserialize(m);
    }
}
于 2012-06-05T20:47:15.677 回答