开发者

Constructor parameter naming for clarity with passing in anonymous methods

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 clarit开发者_开发技巧y (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.


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.

var touchListener = new TouchListener();
touchListener.OnTouchDown += (v,e) => Console.WriteLine("Hehe, I said touchdown");
touchListener.OnTouchUp += (v,e) => Console.WriteLine("Mweh");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜