反序列化对象C#WPF中的空值

时间:2013-02-11 08:50:18

标签: c# wpf serialization null deserialization

我正在序列化一个员工类的对象。类中的某些属性可能为null。我需要使用null值反序列化对象,以便null属性remail null。当我尝试反序列化空值时,我收到TargetInvocationException。请帮帮我

public class Employee
{
   public string Name {get; set;}
   public string Id{get;set;}
}
public mainclass
{
   public void MainMethod()
   {
   Employee emp = new Employee();
   emp.ID = 1;
   //Name field is intentionally uninitialized
   Stream stream = File.Open("Sample.erl", FileMode.Create);
   BinaryFormatter bformatter = new BinaryFormatter();
   bformatter.Serialize(stream, sample);
   stream.Close()
   stream = File.Open("Sample.erl", FileMode.Open);
   bformatter = new BinaryFormatter();
   sample = (Employee)bformatter.Deserialize(stream); //TargetInvocationException here
   //It works fine if Name field is initialized
   stream.Close();
   Textbox1.text = sample.Name;
   Textbox2.text = sample.ID;
   }

}

2 个答案:

答案 0 :(得分:0)

我在LinqPad中尝试了你的代码(有几个mod,上面的代码永远不会编译或工作)。这很好用:

void Main()
{
    Employee emp = new Employee();
    emp.Id = "1";

    const string path = @"C:\Documents and Settings\LeeP\Sample.erl";

    emp.Dump();

    using(var stream = File.Open(path, FileMode.Create))
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, emp);
    }

    using(var stream = File.Open(path, FileMode.Open))
    {
        var formatter = new BinaryFormatter();
        var sample = (Employee)formatter.Deserialize(stream); 

        sample.Dump();
    }
}

// You need to mark this class as [Serializable]
[Serializable]
public class Employee
{
    public string Name {get; set;}
    public string Id{get;set;}
}

答案 1 :(得分:0)

您只需要应用上面提到的必需属性。

namespace SO
{
  using System;
  using System.IO;
  using System.Runtime.Serialization.Formatters.Binary;

  [Serializable]
  public class Employee
  {
    public string Name { get; set; }

    public string Id { get; set; }
  }

  public class Test
  {
    public static void Main()
    {
      var emp = new Employee { Id = "1" };
      //Name field is intentionally uninitialized

      using (var stream = File.Open("Sample.erl", FileMode.Create))
      {
        var bformatter = new BinaryFormatter();

        bformatter.Serialize(stream, emp);
      }

      using (var stream = File.Open("Sample.erl", FileMode.Open))
      {
        var bformatter = new BinaryFormatter();

        var empFromFile = (Employee)bformatter.Deserialize(stream);

        Console.WriteLine(empFromFile.Id);
        Console.ReadLine();
      }
    }
  }
}
相关问题