重构到扩展方法(2):别再写(Action)(delegate(){...})了

话说WPF的Dispatcher类是这样的方法:

 

public DispatcherOperation BeginInvoke(Delegate method, params object[] args);

我们使用的时候不得不这样些:

 

Dispatcher.BeginInvoke((Action)delegate() 

            {

                //Do something...

            });

不觉得丑么?还要强制转换成Action。

可你说,它参数是Delegate,我杂办啊?

呵呵,你忘了扩展方法了?

如果我们能变成:

 

Dispatcher.BeginInvoke(()=>

            {

                //Do something...

            });

这样,该多方便啊,一个Lambda就搞定了。

于是我们自己写个Dispatcher的扩展方法:

 

public static class DispatcherExtensions

    {

        public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action)

        {

            return dispatcher.BeginInvoke(action, new object[0]);

        }



        public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority)

        {

            return dispatcher.BeginInvoke(action, priority, new object[0]);

        }



        public static void Invoke(this Dispatcher dispatcher, Action action)

        {

            dispatcher.Invoke(action, new object[0]);

        }



        public static void Invoke(this Dispatcher dispatcher, Action action, TimeSpan timeout)

        {

            dispatcher.Invoke(action, timeout, new object[0]);

        }



        public static void Invoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority)

        {

            dispatcher.Invoke(action, priority, new object[0]);

        }



        public static void Invoke(this Dispatcher dispatcher, Action action, TimeSpan timeout, DispatcherPriority priority)

        {

            dispatcher.Invoke(action, timeout, priority, new object[0]);

        }

    }

 

 

 

 

 

你可能感兴趣的:(delegate)