C#中的方法链
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1119799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method-Chaining in C#
提问by Patrick
I have actually no idea of what this is called in C#. But i want to add the functionallity to my class to add multiple items at the same time.
我实际上不知道这在 C# 中叫什么。但我想将功能添加到我的班级以同时添加多个项目。
myObj.AddItem(mItem).AddItem(mItem2).AddItem(mItem3);
采纳答案by LBushkin
The technique you mention is called chainable methods. It is commonly used when creating DSLs or fluent interfacesin C#.
您提到的技术称为可链接方法。它通常用于在 C# 中创建 DSL 或流畅的接口。
The typical pattern is to have your AddItem() method return an instance of the class (or interface) it is part of. This allows subsequent calls to be chained to it.
典型的模式是让您的 AddItem() 方法返回它所属的类(或接口)的实例。这允许后续调用链接到它。
public MyCollection AddItem( MyItem item )
{
// internal logic...
return this;
}
Some alternatives to method chaining, for adding items to a collection, include:
用于将项目添加到集合的方法链的一些替代方法包括:
Using the params
syntax to allow multiple items to be passed to your method as an array. Useful when you want to hide the array creation and provide a variable argument syntax to your methods:
使用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 );
Providing an overload of type IEnumerable or IEnumerable so that multiple items can be passed together to your collection class.
提供 IEnumerable 或 IEnumerable 类型的重载,以便可以将多个项目一起传递到您的集合类。
public void AddItems( IEnumerable<MyClass> items )
{
foreach( var item in items )
m_innerCollection.Add( item );
}
Use .NET 3.5 collection initializer syntax. You class must provide a single parameter Add( item )
method, implement IEnumerable, and must have a default constructor (or you must call a specific constructor in the initialization statement). Then you can write:
使用 .NET 3.5 集合初始值设定项语法。您的类必须提供单参数Add( item )
方法,实现 IEnumerable,并且必须具有默认构造函数(或者您必须在初始化语句中调用特定的构造函数)。然后你可以写:
var myColl = new MyCollection { first, second, third, ... };
回答by User
Use this trick:
使用这个技巧:
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;
}
}
It returns the current instance which will allow you to chain method calls (thus adding multiple objects "at the same time".
它返回当前实例,这将允许您链接方法调用(从而“同时”添加多个对象。
回答by Tim Hoolihan
If your item is acting as a list, you may want to implement an interface like iList or iEnumerable / iEnumerable.
如果您的项目用作列表,您可能需要实现一个接口,如 iList 或 iEnumerable / iEnumerable。
Regardless, the key to chaining calls like you want to is returning the object you want.
无论如何,像您想要的那样链接调用的关键是返回您想要的对象。
public Class Foo
{
public Foo AddItem(Foo object)
{
//Add object to your collection internally
return this;
}
}
回答by Mats Fredriksson
Something like this?
像这样的东西?
class MyCollection
{
public MyCollection AddItem(Object item)
{
// do stuff
return this;
}
}
回答by Martin Liversage
How about
怎么样
AddItem(ICollection<Item> items);
or
或者
AddItem(params Item[] items);
You can use them like this
你可以像这样使用它们
myObj.AddItem(new Item[] { item1, item2, item3 });
myObj.AddItem(item1, item2, item3);
This is not method chaining, but it adds multiple items to your object in one call.
这不是方法链,而是在一次调用中向您的对象添加多个项目。
回答by Marc Gravell
"I have actually no idea of what this is called in c#"
“我实际上不知道在 c# 中这叫什么”
A fluent API; StringBuilder
is the most common .NET example:
流畅的API;StringBuilder
是最常见的 .NET 示例:
var sb = new StringBuilder();
string s = sb.Append("this").Append(' ').Append("is a ").Append("silly way to")
.AppendLine("append strings").ToString();
回答by Jon Skeet
Others have answered in terms of straight method chaining, but if you're using C# 3.0 you might be interested in collection initializers... they're only available when you make a constructor call, and only if your method has appropriate Add
methods and implements IEnumerable
, but then you can do:
其他人已经回答了直接方法链接,但是如果您使用的是 C# 3.0,您可能对集合初始值设定项感兴趣......它们仅在您进行构造函数调用时可用,并且仅当您的方法具有适当的Add
方法和实现IEnumerable
,但是你可以这样做:
MyClass myClass = new MyClass { item1, item2, item3 };
回答by bruno conde
回答by GC.
You could add an extension method to support this, provided your class inherits from ICollection:
您可以添加一个扩展方法来支持这一点,前提是您的类继承自 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;
}
}