How to serialize a delegate

Let's look at an example of filling a grid.

We have a Column class . It has a FormatCell delegate that takes some data and converts it to a string. The FormatCell delegate is unknown at design time - it can be installed by the plugin.

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

Here is an example of using such columns.

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 maintain its state. And the question is how to serialize this FormatCell delegate?

PS I know this question , but my question is much more specific. And, perhaps, for such a case there is a special reliable solution?

+3
source share
1 answer

? . - :

[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 //;
    }
}

, ColumnFormatterBase - .

+1

All Articles