链式方法调用在C# [英] Method-Chaining in C#

查看:246
本文介绍了链式方法调用在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实我也没有什么这就是所谓的在C#中的想法。
但我想后的功能添加到我的同班同学,同时添加多个项目。

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


解决方案

你所提到的技术被称为链式方法。创建的DSL或流利的接口时,它通常用于的在C#。

典型的模式是有你的AddItem()方法返回的类(或接口)的实例,它的一部分。这使得后续调用被链接到它。

 公共MyCollection的的AddItem(MyItem项)
{
   //内部逻辑...   返回此;
}

一些替代方法链接,添加物品的集合,包括:

使用 PARAMS 语法允许多个项目要传递给你的方法作为数组。有用的,当你要隐藏的阵列创建和你的方法提供了可变参数的语法:

 公共无效为addItems(PARAMS MyItem []项)
{
    的foreach(在项目VAR项)
        m_innerCollection.Add(项目);
}//可与任意数量的参数调用...
coll.AddItems(第一,第二,第三);
coll.AddItems(第一,第二,第三,第四,第五);

提供了IEnumerable类型或IEnumerable的过载,使多个项目可以传递到一起的集合类。

 公共无效为addItems(IEnumerable的< MyClass的>的项目)
{
    的foreach(在项目VAR项)
         m_innerCollection.Add(项目);
}

使用.NET 3.5集合初始化语法。你的类必须提供一个参数添加(项目)方法,实现IEnumerable,并且必须有一个默认的构造函数(或者你必须调用初始化语句的特定构造)。然后,你可以这样写:

  VAR MYCOLL =新MyCollection的{第一,第二,第三,...};

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.

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

解决方案

The technique you mention is called chainable methods. It is commonly used when creating DSLs or fluent interfaces in C#.

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.

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:

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.

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:

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

这篇关于链式方法调用在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆