2

这可能是一个愚蠢的问题,但是我有一种方法可以使页面的语法更易于阅读

    public void Do(Delegate method, DispatcherPriority priority = DispatcherPriority.Normal)
    {
        this.Window.Dispatcher.BeginInvoke(method, DispatcherPriority.Background);
    }

然后我可以写

        Do(new Action(() =>
        {
            //DoStuff()
        }));

但是,我想将 Action 移到 Do 方法中,这样我就可以写得更简单:

        Do(() =>
        {
            //DoStuff()
        }));

但我有点确定如何编写逆变参数来执行 Do 方法?

4

1 回答 1

4

Lambda 是无类型的,所以这是不可能的。

如果您不关心方法参数(似​​乎是这种情况),为什么不将方法签名更改为:

public void Do(Action method,
               DispatcherPriority priority = DispatcherPriority.Normal)

然后,第二个示例将正常工作,因为编译器将能够将 lambda 隐式转换为Action.

如果你真的想接受代表不带参数的方法的任何委托类型的实例,你将不得不坚持你目前拥有的东西。

于 2010-12-20T12:05:18.947 回答