SerializationException,如何避免UserControl消耗一个要序列化的事件?

时间:2011-08-03 22:30:32

标签: .net vb.net serialization user-controls

我尝试序列化一个对象,它会抛出异常,如下所示。我假设它尝试序列化UserControl,它包含在我尝试序列化的类的事件中。这是不希望的。那么如何避免序列化事件? (尽可能简单)

发生了SerializationException:

  

键入' System.Windows.Forms.UserControl'在大会   ' System.Windows.Forms,Version = 2.0.0.0,Culture = neutral,   公钥= b77a5c561934e089'未标记为可序列化。

Public Sub SendData(ByVal obj As Object)

    If Client.Connected Then
        Try
            Dim ns As NetworkStream = Client.GetStream()

            Dim bf = New BinaryFormatter()
            Dim ms = New MemoryStream()

            bf.Serialize(ms, obj)   ' < Exception here

4 个答案:

答案 0 :(得分:2)

  

如何避免序列化事件?

解决方案是使用[NonSerialized]属性标记班级中的事件处理程序。

答案 1 :(得分:0)

您传递到日常工作中的对象似乎不可序列化。您是否将usercontrol传递给此方法?如果是这样,你需要传递你想要序列化的东西,我认为它可能是其中的数据结构?否则,请尝试使用对象上的[Searilzable]属性,看看是否有效。

答案 2 :(得分:0)

一种选择是实施ISerializable并仅序列化您想要的内容。

C#可用的另一个选项(我不确定VB)是自定义添加/删除代码。

[NonSerialized]  // prevents the m_changed field from being serialized.
private EventHandler m_changed;

public event Changed
{
  add
  {
    m_changed += value;
  }
  remove
  {
    m_changed -= value;
  }
}

答案 3 :(得分:0)

VB.NET不允许事件属性。由于VB.NET实现事件的方式,当您序列化对象时,其事件也会被序列化,因为事件实际上是使用隐藏的多播委托字段实现的。以下是在vb中序列化期间如何删除处理程序的示例:

      <NonSerialized()> _
  Private PropertyChangedHandlers As New Generic.List(Of PropertyChangedEventHandler)

  ''' <summary>
  ''' stores parameter of event in a local nonserializable variable
  ''' </summary>
  ''' <remarks></remarks>
  Public Custom Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
     AddHandler(ByVal value As PropertyChangedEventHandler)
        If PropertyChangedHandlers Is Nothing Then
           PropertyChangedHandlers = New Generic.List(Of PropertyChangedEventHandler)()
        End If
        PropertyChangedHandlers.Add(value)
     End AddHandler

     RemoveHandler(ByVal value As PropertyChangedEventHandler)
        If value Is Nothing Or PropertyChangedHandlers Is Nothing Then
           Return
        End If

        PropertyChangedHandlers.Remove(value)
     End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
            Dim pos As Int32
            Dim count As Int32
            Dim Element As PropertyChangedEventHandler
            If Me.PropertyChangedHandlers IsNot Nothing Then
                count = PropertyChangedHandlers.Count
                If count > 0 Then
                    For pos = (count - 1) To 0 Step -1
                        Element = PropertyChangedHandlers(pos)
                        Try
                            Element.Invoke(sender, e)
                        Catch ex As Exception
                            'Ignore any error generated
                        End Try
                    Next
                End If
            End If
        End RaiseEvent
  End Event