我有这样的方法:
public void DoSomething( .... , bool orderByX)
{
if(orderByX)
{
foreach( ... OrderBy(x => x.Location.X))
{
...
}
}
else
{
foreach( ... OrderBy(x => x.Location.Y)
{
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想避免if产生较少重复的代码(即只有一个foreach).这可能吗?
谢谢.
Ily*_*nov 15
更好的方法是通过标准,按顺序排序.您可以使用下一个代码作为动机:
public void DoSomething<T>( .... , Func<Point, T> orderbySelector)
{
foreach( ... OrderBy(p => orderbySelector(p.Location)))
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以:
DoSomething(mySequence, point => point.X)
Run Code Online (Sandbox Code Playgroud)
要么
DoSomething(mySequence, point => point.Y)
Run Code Online (Sandbox Code Playgroud)
注意:您可以根据需要概括选择器(例如传递持有者,或者Location代替Point自身).
此外,bool作为排序标准传递使代码可读性降低.例如,我不知道这个方法做了什么,只需查看它的调用DoSomething(list, false),我必须看到方法签名,以便知道什么是语义false.使用命名参数DoSomething(list, orderByX : false)(可从C#4.0获得)会好得多,但是如果我没有订购X,我怎么知道,那我订购了Y?.这也限制了调用代码只有两个排序标准(你不想添加另一个排序标志,不是吗?)
因此,您需要打开您的意图DoSomething,使您的名字显露出来,您实际上是在订购您的处理.例如TraverseNodesOrderedBy(nodes, point => point.X)