什么是正确的方式在.net链方法 [英] What is the correct way to chain methods in .Net

查看:155
本文介绍了什么是正确的方式在.net链方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,可以链方法返回一个值或使用无效。是他们中的一个正道?

In .Net, you can chain methods returning a value or by using a void. Is one of them the "right way"?

所以,你可以说

1)

Foo myFoo = new Foo();
myfoo.Bars = 
  myBars.DoSomethingCool(x)
  .DoSomethingElse(y)
  .AndSomethingElse(z);

public static IList<IBar> DoSomethingCool(this IList<IBar> source, object x)
{
  IList<IBar> result = //some fn(source)
  return result;
}

在这种情况下,所有3个扩展方法需要返回的IList(用于myFoo.Bars类型)

In this case, all 3 extension methods need to return IList (the type for myFoo.Bars)

,或者它也可以写成

2)

myBars.DoSomethingCool(x)
.DoSomethingElse(y)
.AndSomethingElse(z);

public static void DoSomethingCool(this IList<IBar> source, object x)
{
  //Modify source
  source = //some fn(source)
  //Don't return anything
}

在这种情况下,扩展方法返回一个空,但是做源对象,是未来在工作?

in which case, the extension methods return a void, but do the work on the source object that's coming in?

更新西蒙在他的回答是2正确的)将无法编译。下面是如何可以重新编写:

UPDATE Simon was correct in his answer that 2) won't compile. Here is how that could be re-written:

DoSomethingCool(myBars)
.DoSomethingElse(myBars)
.AndSomethingElse(myBars);

myBars将被改变每个方法的调用内部和方法将返回void。

myBars would then be changing inside the call of each method and the methods would be returning void.

推荐答案

1)获胜。西门正确回答2)将不能编译,但他做到了为注释,所以我不能GIE他的信用回答。 2更新的解决方案)做一切的副作用是我想不出一个理由,你为什么会愿意做,在一个静态类型语言。

1) wins. Simon correctly answered that 2) wouldn't compile, but he did it as a comment, so I can't gie him credit for answering. The updated solution for 2) does everything as a side effect an I can't think of a reason why you would ever want to do that in a statically typed language.

在关于链接的调试问题的点都是要考虑的事情,但我发现链接过滤时特别有用。

The points made about chaining's debugging issue are something to consider, though I find chaining to be especially useful when filtering.

mybars.FilterByHasHappyHour()

BigGiantUtilityClass.GetBarsWithHappyHours(myBars)

这篇关于什么是正确的方式在.net链方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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