Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a delegate

Lets look at an example of grid filling.

We have Column class. It has a delegate FormatCell, which take some Data and convert it to a string. FormatCell delegate is unknown at design time - it might be set by a plugin.

public class ColumnFormatter
{
    public Func<Data, string> FormatCell {get; set;}
    //...
}

Here is an example of how such Columns are used.

public class Table
{
    public List<Column> Columns;

    public List<List<string>> BuildTable(List<Data> dataRows)
    {
        var table = new List<List<string>>();

        foreach (var data in dataRows)
        {
            var line = new List<string>();                    
            foreach (var column in Columns)
            {
                line.Add(column.FormatCell(data));
            }

            table.Add(line);
        }

        return table;
    }
}

Now each column should save its state. And the question is how to serialize this FormatCell delegate?

P.S. I'm aware of this question but my question is much more case specific. And maybe one has a specific reliable run-in solution for the such case?

like image 706
MajesticRa Avatar asked Nov 14 '22 06:11

MajesticRa


1 Answers

Why don't just use inheritance? And not to try serialize delegate. Something like this:

[Serializable]
public abstract class ColumnFormatterBase
{
    public abstract string FormatCell(Data data);
}

[Serializable]
public class ColumnFormatter1: ColumnFormatterBase
{
    object SerializableProperty1 {get; set;}
    object SerializableProperty2 {get; set;}
    public override string FormatCell(Data data)
    {
        return // formatted result //;
    }
}

It can be serialized, even if implementation of ColumnFormatterBase is located somewhere in plugin assembly.

like image 99
The Smallest Avatar answered Nov 16 '22 04:11

The Smallest