【问题标题】:Method-Chaining in C#C# 中的方法链
【发布时间】:2009-07-13 14:31:57
【问题描述】:

我实际上不知道这在 C# 中叫什么。 但我想将功能添加到我的类中以同时添加多个项目。

myObj.AddItem(mItem).AddItem(mItem2).AddItem(mItem3);

【问题讨论】:

标签: c#


【解决方案1】:

您提到的技术称为可链接方法。在 C# 中创建 DSL 或 fluent interfaces 时常用。

典型的模式是让您的 AddItem() 方法返回它所属的类(或接口)的实例。这允许将后续调用链接到它。

public MyCollection AddItem( MyItem item )
{
   // internal logic...

   return this;
}

方法链的一些替代方法,用于将项目添加到集合中,包括:

使用params 语法允许将多个项目作为数组传递给您的方法。当您想要隐藏数组创建并为您的方法提供变量参数语法时很有用:

public void AddItems( params MyItem[] items )
{
    foreach( var item in items )
        m_innerCollection.Add( item );
}

// can be called with any number of arguments...
coll.AddItems( first, second, third );
coll.AddItems( first, second, third, fourth, fifth );

提供 IEnumerable 或 IEnumerable 类型的重载,以便可以将多个项目一起传递给您的集合类。

public void AddItems( IEnumerable<MyClass> items )
{
    foreach( var item in items )
         m_innerCollection.Add( item );
}

使用 .NET 3.5 集合初始化语法。您的类必须提供单个参数Add( item ) 方法,实现 IEnumerable,并且必须具有默认构造函数(或者您必须在初始化语句中调用特定构造函数)。然后你可以写:

var myColl = new MyCollection { first, second, third, ... };

【讨论】:

  • +1 学到了新东西 :D 我认为我必须为 chaning 方法制作不同的方法
【解决方案2】:

使用这个技巧:

public class MyClass
{
    private List<MyItem> _Items = new List<MyItem> ();

    public MyClass AddItem (MyItem item)
    {
        // Add the object
        if (item != null)
            _Items.Add (item)

        return this;
    }
}

它返回允许您链接方法调用的当前实例(从而“同时”添加多个对象。

【讨论】:

    【解决方案3】:

    “我其实不知道这在c#中叫什么”

    流畅的 API; StringBuilder 是最常见的 .NET 示例:

    var sb = new StringBuilder();
    string s = sb.Append("this").Append(' ').Append("is a ").Append("silly way to")
         .AppendLine("append strings").ToString();
    

    【讨论】:

      【解决方案4】:

      其他人已经回答了直接方法链接,但如果您使用的是 C# 3.0,您可能会对 集合初始化器感兴趣...它们仅在您调用构造函数时可用,并且仅当您的类型具有适当的 Add 方法并实现 IEnumerable 时,您才可以这样做:

      MyClass myClass = new MyClass { item1, item2, item3 };
      

      【讨论】:

        【解决方案5】:

        为什么不使用params 关键字?

        public void AddItem (params MyClass[] object)
        {
            // Add the multiple items
        }
        

        【讨论】:

          【解决方案6】:

          如果你的类继承自 ICollection,你可以添加一个扩展方法来支持这一点:

          [TestClass]
          public class UnitTest1
          {
              [TestMethod]
              public void CanChainStrings()
              {
                  ICollection<string> strings = new List<string>();
          
                  strings.AddItem("Another").AddItem("String");
          
                  Assert.AreEqual(2, strings.Count);
              }
          }
          
          public static class ChainAdd
          {
              public static ICollection<T> AddItem<T>(this ICollection<T> collection, T item)
              {
                  collection.Add(item);
                  return collection;
              }
          }
          

          【讨论】:

            【解决方案7】:

            怎么样

            AddItem(ICollection<Item> items);
            

            AddItem(params Item[] items);
            

            你可以这样使用它们

            myObj.AddItem(new Item[] { item1, item2, item3 });
            myObj.AddItem(item1, item2, item3);
            

            这不是方法链接,但它在一次调用中将多个项目添加到您的对象中。

            【讨论】:

              【解决方案8】:

              如果您的项目用作列表,您可能希望实现类似 iList 或 iEnumerable / iEnumerable 的接口。

              无论如何,像你想要的那样链接调用的关键是返回你想要的对象。

              public Class Foo
              {
                 public Foo AddItem(Foo object)
                 {
                      //Add object to your collection internally
                      return this;
                 }
              }
              

              【讨论】:

                【解决方案9】:

                这样的?

                class MyCollection
                {
                    public MyCollection AddItem(Object item)
                    {
                        // do stuff
                        return this;
                    }
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2016-06-11
                  • 2012-09-20
                  • 2016-06-11
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2017-08-25
                  • 2021-03-18
                  相关资源
                  最近更新 更多