Serializing a list of anonymous delegates

你说的曾经没有我的故事 提交于 2019-12-03 17:37:53

It usually makes very little sense to serialize a delegate. Normally, you would choose to mark delegate fields as [NonSerialized], and recreate it when needed. If your main intent is to store the delegates, then I would recommend thinking of a completely different approach, frankly.

Additionally, note that BinaryFormatter is brittle if you are planning to keep the data for any length of time (but acceptable for transient data)

To look further, I suspect we'd need to look at some reproducible code.


Update: actually, I suspect you could serialize it by writing your own explicit capture classes (rather than the compiler-generated ones). But I still think the concept is fundamentally flawed. And writing capture classes by hand isn't fun.


To address the points in comments; re long term storage - because it is so darned brittle - something as simple as changing from:

public int Value {get;set;}

to

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

will destroy serialization; as will changing assemblies, type names, "looking at it funny", etc.

Re the delegates; to give an example of a manual capture; instead of:

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

you might do:

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

with

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

As you can see - not always trivial (this is the simplest of examples).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!