我实际上不知道在C#中这叫什么。但是我想向我的班级添加功能,以同时添加多个项目。
myObj.AddItem(mItem).AddItem(mItem2).AddItem(mItem3);
Answers:
您提到的技术称为可链接方法。在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, ... };
使用这个技巧:
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;
}
}
它返回当前实例,该实例将允许您链接方法调用(从而“同时”添加多个对象)。
“我实际上不知道在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();
如果您的类继承自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;
}
}
如果您的商品充当列表,则可能需要实现iList或iEnumerable / iEnumerable之类的接口。
无论如何,链接所需链接的关键是返回所需对象。
public Class Foo
{
public Foo AddItem(Foo object)
{
//Add object to your collection internally
return this;
}
}
像这样吗
class MyCollection
{
public MyCollection AddItem(Object item)
{
// do stuff
return this;
}
}