为了清楚地传递匿名方法,构造函数参数命名
当将匿名方法传递给委托参数时,我对代码的可读性感兴趣:
var touchListener = new TouchListener(
down:(v, e) =>
{
//Handle the down event
},
up:(v, e) =>
{
//Handle the up event
});
正如您所看到的,我已将参数命名为向下和向上,以便更明显地显示这些匿名方法正在做什么。
为了清楚起见,这里是 TouchListener 类(它针对 MonoDroid 工作,但这在这里并不重要):
public class TouchListener : View.IOnTouchListener
{
public delegate void OnTouchAction(View v, MotionEvent e);
private OnTouchAction down;
private OnTouchAction up;
public TouchListener(OnTouchAction down, OnTouchAction up)
{
this.down = down;
this.up = up;
}
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
this.down(v,e);
break;
case MotionEventActions.Up:
this.up(v,e);
break;
default:
break;
}
return true;
}
}
也许我的方法是错误的,并且我过度使用了匿名方法?然而,它节省了大量代码。
I'm interested in the readability of my code when passing anonymous methods into delegate parameters:
var touchListener = new TouchListener(
down:(v, e) =>
{
//Handle the down event
},
up:(v, e) =>
{
//Handle the up event
});
As you can see I have named the parameters down and up, so that it is more obvious what these anonymous methods are doing.
Here is the TouchListener class for clarity (it is working against MonoDroid, but that isn't important here):
public class TouchListener : View.IOnTouchListener
{
public delegate void OnTouchAction(View v, MotionEvent e);
private OnTouchAction down;
private OnTouchAction up;
public TouchListener(OnTouchAction down, OnTouchAction up)
{
this.down = down;
this.up = up;
}
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
this.down(v,e);
break;
case MotionEventActions.Up:
this.up(v,e);
break;
default:
break;
}
return true;
}
}
Perhaps my approach is wrong, and I am overusing anonymous methods? However it is saving a lot of code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 Javascript/jQuery 的角度来看,这是非常清晰的代码;即使没有命名参数。随意使用匿名函数就是处理事件的方式。
然而,从 C# 的角度来看,这是相当不清楚的。 (几乎?).NET 库都没有使用匿名函数来处理事件。因此,为了省去麻烦,只需使用真实事件即可。
From a Javascript / jQuery perspective, this is pretty clear code; even without the named parameters. Tossing anonymous functions around is just the way events are handled.
However, from a C# perspective it's pretty unclear. (Almost?) none of the .NET library uses anonymous functions for event-handling. So save yourself the hassle and just use real events for this.