代码之家  ›  专栏  ›  技术社区  ›  R. Martinho Fernandes

在列表之间“移动”对象的首选方法

  •  0
  • R. Martinho Fernandes  · 技术社区  · 15 年前

    我有两个单独的实体列表:

    class EntityCollection : IList<Entity>
    {
        //...
    }
    
    EntityCollection Foo;
    EntityCollection Bar;
    

    我想实现一个移动对象的操作 Qux 这在FOO到BAR的名单上。实现它的最佳方法是什么?

    • 作为一个 MoveTo 上的实例方法 EntityCollection :

      public void MoveTo(EntityCollection to, Entity entity);
      
      // Client code
      Foo.MoveTo(Bar, Qux);
      
    • 作为一个 MoveFrom 上的实例方法 实体集合 :

      public void MoveFrom(EntityCollection from, Entity entity);
      
      // Client code
      Bar.MoveFrom(Foo, Qux);
      
    • 作为静态 Move 方法对 实体集合 :

      public static void Move(Entity entity, EntityCollection from, EntityCollection to);
      
      // Client code
      EntityCollection.Move(Qux, Foo, Bar);
      
    • 作为一个 移动 包含两个集合的类上的实例方法:

      public void Move(Entity entity, EntityCollection from, EntityCollection to);
      
      // Client code
      Holder.Move(Qux, Foo, Bar);
      

    或者,由于实体一次只能在一个集合中,我可以让实体自己跟踪其位置,并在实体本身上实现它:

        public void MoveTo(EntityCollection to)
        {
           if(Location != null)
               Location.Remove(this);
           to.Add(this);
           Location = to;
        }
    
        // Client code
        Entity e;
        e.MoveTo(Foo);
    
        // Later on...
        e.MoveTo(Bar);
    

    当有这么多选项时,我想知道:move方法属于哪里?为什么?

    3 回复  |  直到 15 年前
        1
  •  1
  •   phillipwei    15 年前

    归根结底,我不认为这件事太重要,所以我的软回答是不要担心。

    从语言上讲,moveto似乎比movefrom更自然——尽管我可以想象实现这两个都是为了完整性。

    从概念上讲,我觉得集合实例和被移动的实体都不是移动的“负责人”,这可能会让我倾向于将其作为静态方法——否则,您将在操作中对这三件事情之一赋予一些额外的重要性。

    建造一个支架来完成这个动作似乎太过分了。

    但这取决于你自己,更多关于这些东西通常是如何消费的知识可能会告诉你什么是“正确的”解决方案。

        2
  •  1
  •   Jacob Ewald    15 年前

    moveTo和moveFrom都将使用对add()和remove()的调用,这样您就可以在一个函数中同时执行这两个操作。在这种情况下,您可以这样做:

    enum MoveDirection
    {
        ToFoo = 0
        ToBar = 1
    }
    
    MoveItem(Entity entity, MoveDirection direction)
    {
        if direction = 0
           //move entity from Bar to Foo
        elseif direction = 1
           //move entity from Foo to Bar
        endif
    }
    
        3
  •  0
  •   R. Martinho Fernandes    15 年前

    使用扩展方法怎么样?

    客户代码为:

    Foo.Move(Qux).To(Bar);
    

    签名:

    public static Entity Move(this EntityCollection from, Entity entity)
    public static void To(this Entity entity, EntityCollection to)
    

    Fluent !