2

Первый раз столкнулся с сериализацией. Есть класс

    [Serializable()]
   [ComVisibleAttribute(false)]
  public class Message : ISerializable
  {
    public String user;
    public String messageText;
    public String command;
    public List<String> userList;

    public Message(String u,String c,String t,List<String> uList)
    { 
        user=u;
        messageText=t;
        command=c;
        userList = new List<string>();
        if (uList != null) userList =new List<String>(uList);

    }
    public Message(SerializationInfo info, StreamingContext context)
    {
        command = info.GetString("command");
        user = info.GetString("user");
        messageText = info.GetString("messageText");        
        var val  = (String[])info.GetValue("userList", typeof(String[]));
        for (int i = 0; i < val.Count(); i++)
            userList.Add(val[i]);
    }

    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("user", user);
        info.AddValue("messageText", messageText);
        info.AddValue("command", command);
        info.AddValue("userList", userList.ToArray());
    }
}

Тестовая программа

static void Main(string[] args)
    {
        var uList = new List<String>();
        uList.Add("1");
        uList.Add("2");
        uList.Add("3");
        Message msg = new Message("1", "2", "3", uList);
        MemoryStream memoryStream = new MemoryStream();
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(memoryStream, msg);
        Stream stream = new MemoryStream(memoryStream.ToArray());
        Message message = (Message)formatter.Deserialize(stream);
    }

При выполнении последней строки вылетает эксепшен

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dllAdditional information: Exception has been thrown by the target of an invocation.

Если вместо списка передавать null, то все нормально

1 ответ 1

2

В конструкторе

public Message(SerializationInfo info, StreamingContext context)

Перед циклом занесением элемнтов список userList Вы его не инициализировали.

P.S. Пользуйтесь отладчиком - он незаменим:)

1
  • Да, спасибо, дело было в этом.
    – Rejjell
    27 апр 2013 в 15:11

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.