【问题标题】:Serializable with IEnumerable Property and a List Member可使用 IEnumerable 属性和列表成员进行序列化
【发布时间】:2017-04-02 17:25:35
【问题描述】:

今天我在我们的代码库中发现了一颗宝石......

[Serializable]
public class MonsterClass
{
    // Interfaces are good, especially for testing
    public IEnumerable<FooBar> FooBars
    {
        get { return m_FooBars; }

        // rationale = clever linq performance trick/safeguard
        set { m_FooBars = new List(value); }
    }

    // alas ... it is serializable, thus we REQUIRE, it to be a List
    private List<FooBar> m_FooBars;

    //...
    //ton loads of methods, performing tricks on list of FooBar and other types
    //...
}

我想重构这个怪物类,删除所有执行的方法 IEnumerable 到一个新的 FooBarList 类中。

问题:以下内容是否可以安全替代?虽然它仍然可以序列化!

[Serializable]
public class FooBarList : List<FooBar>, IEnumerable<FooBar>
{
    public FooBarList(IEnumerable<FooBar> fooBars)
    {
        this = new List<FooBar>(fooBars);
    }

    //move specific methods here
}

[Serializable]
public class MonsterClass
{
    public FooBarList FooBars { get; set; }

    //still monsterclass, but now the FooBars are refactored out
}

或者它是一个更好的主意,并通过使用扩展方法采取懒惰/鸡的方式? (旁注:由于性能影响和重构时间,我排除了重构此类的选项,方法是在两者之间添加域模型和适配器)

【问题讨论】:

  • 这里使用扩展方法有什么缺点?如果没有任何缺点,您应该使用扩展方法。
  • @TannerSwett 这不合逻辑,因为我们完全控制了这些课程。
  • IEnumerable&lt;FooBar&gt;上定义扩展方法有什么不合逻辑的?
  • @TannerSwett 请参阅 MSDN 关于扩展方法的一般指南 (msdn.microsoft.com/en-us/library/bb383977.aspx),但毕竟我可能会考虑这个选项,因为我们也处于高性能要求的环境中。

标签: c# serializable


【解决方案1】:

您没有通过使用自定义类来完成任何事情。如果您不希望此类抽象出它需要存储List 而不是IEnumerable 的事实,则将属性设为List 并强制调用者转换任何非列表@987654324 @ 他们已经进入了一个列表(考虑到他们无论如何都需要用你的自定义列表来做同样的士气)。

到那时,这只是一个问题,即此类的消费者是否认为能够分配任意非列表 IEnumerable 很有用,而无需先将其转换为列表,或者如果这个复杂性上课对你来说不值得。

【讨论】:

    【解决方案2】:

    在这种特定情况下,最好的替代方法是在 IEnumerable&lt;FooBar&gt; 上使用扩展方法,而不是使用 Composition。

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 2022-01-19
      • 1970-01-01
      • 2012-06-08
      相关资源
      最近更新 更多