如何序列化的委托 [英] How to serialize a delegate

查看:145
本文介绍了如何序列化的委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看网格填充的一个例子。

Lets look at an example of grid filling.

我们拥有的类。它有一个委托的 FormatCell ,这需要一定的数据并把它转换为一个字符串 FormatCell 委托在设计时未知的 - 它可能是由一个插件来设置。

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

现在每列应该保存其状态。而问题是如何序列化此FormatCell委派?

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

P.S。我知道这个问题但我的问题得多的情况下的特定。也许一个人在这种情况下特定的可靠运行的解决方案?

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?

推荐答案

为什么不只是使用继承?而不要尝试序列化委托。事情是这样的:

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



即使实现ColumnFormatterBase的是它可以被序列化,位于某处的插件组装。

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

这篇关于如何序列化的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆