What is the correct way to chain methods in .Net

╄→гoц情女王★ 提交于 2019-12-07 13:10:29

问题


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

So you could say

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

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

or it could also be written as

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?

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 would then be changing inside the call of each method and the methods would be returning void.


回答1:


In both cases you're using an extension method, returning an object, and then using that object as the input to the next method in the chain. The second example is close to a Fluent Interface (but not quite). I think in your two examples the critical distinction is one of mutability. Do you want the original input to be modified (the second example) or not (the first example)? The "correct" answer depends on the situation and context.




回答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() is much nicer than

BigGiantUtilityClass.GetBarsWithHappyHours(myBars)


来源:https://stackoverflow.com/questions/6687528/what-is-the-correct-way-to-chain-methods-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!