C#中的方法链


Answers:


121

您提到的技术称为可链接方法。在C#中创建DSL或流畅接口时,通常使用它。

典型的模式是让您的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
+1学到了很多新东西:D我以为我要为诵经方法做出另一种方法
GaryNg 2013年

33

使用这个技巧:

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

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


不需要将AddItem的参数限制为MyClass。可能是对象,项目或其他东西。
Mats Fredriksson,2009年

15

“我实际上不知道在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();

11

其他人已经回答了直接方法链接的问题,但是如果您使用的是C#3.0,则可能对集合初始化程序感兴趣……它们仅在进行构造函数调用时可用,并且仅在您的方法具有适当的Add方法和实现时可用IEnumerable,但是您可以执行以下操作:

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


4

如果您的类继承自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;
    }
}

3

怎么样

AddItem(ICollection<Item> items);

要么

AddItem(params Item[] items);

您可以像这样使用它们

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

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


1

如果您的商品充当列表,则可能需要实现iList或iEnumerable / iEnumerable之类的接口。

无论如何,链接所需链接的关键是返回所需对象。

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.