I know why code like as shown below throws that exception, but I don't know
how to prevent it. If I make private or protected the delegate declaration I
can't define public the event accessor obviously. Any hints?
[Serializable]
class Class2
{
public delegate void MyDelegateFunc(int i);
private event MyDelegateFunc myEvent;
public event MyDelegateFunc AccessMyEvent
{
add
{
myEvent += value;
}
remove
{
myEvent -= value;
}
}
}
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Class2 c = new Class2();
c.AccessMyEvent +=new
DelegateTest.Class2.MyDelegateFunc(c_AccessMyEvent);
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream("test.dat",FileMode.Create);
bf.Serialize(fs, c);
fs.Flush();
fs.Close();
fs = new FileStream("test.dat", FileMode.Open);
c = (Class2)bf.Deserialize(fs);
fs.Close();
}
public static void c_AccessMyEvent(int i)
{
}
}
Clayton Gulick said:
Even though the method is non-public, the delegate itself is a first class
object which does not support serialization, therefore you will have to
declare the delegate protected or private and make accessor methods to
assign it. If the delegate declaration is public, your class will not
serialize.