Serializing the Anonymous Delegate List

This question may be very similar to mine, but I do not see the answer that I need. I have a class called CASMthat has List<Action>. I want to serialize this class (using BinaryFormatteror something similar). This class and all the classes referenced in Actionreceived the correct attributes [Serializable]and [NonSerializable].

The problem occurs when trying to serialize - it gives this error:

Type 'CASM.CASM+<>c__DisplayClass2c' in Assembly 'CASM, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null' is not marked as serializable.

This <>c__DisplayClass2cis a self-generated inner class that contains the various types of anonymous delegates that I use in my application. However, as can be seen from the image below, this is not [Serializable]:

alt text http://bayimg.com/image/maebbaacj.jpg

What would be the best way to change my application for this to work? Create your own <>c__DisplayClass2c-type class and make it serializable? Or is there a better way?


EDIT: In the end, I just created my own class, not auto-generated. I also help debug, actually having a descriptive name, not just that b__12().

+3
source share
1 answer

. [NonSerialized] , . , , , .

, , BinaryFormatter , ( )

, , - .


: , , , ( ). , . - .


; - - - , :

public int Value {get;set;}

private int value;
public int Value {
    get {return value;}
    set {
        if(value < 0) throw new ArgumentOutOfRangeException();
        this.value = value;
    }
}

; , , " " ..

; ; :

int i = ...
Predicate<Foo> test = delegate (Foo x) { return x.Bar == i;}

:

int i = ...
MyCapture cpt = new MyCapture(i);
Predicate<Foo> test = cpt.MyMethod;

[Serializable]
class MyCapture {
    private int i;
    public MyCapture(int i) {this.i = i;}
    public bool MyMethod(Foo x) {return x.Bar == i;}
}

- ( ).

+4

Source: https://habr.com/ru/post/1720976/


All Articles