【问题标题】:Contravariant parameters?逆变参数?
【发布时间】:2010-12-20 12:00:38
【问题描述】:

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

    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 方法?

【问题讨论】:

    标签: c# lambda delegates c#-4.0 contravariance


    【解决方案1】:

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

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

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

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

    如果您真的想接受代表不带参数的方法的 any 委托类型的实例,则必须坚持使用当前所拥有的方法。

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2012-03-26
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      相关资源
      最近更新 更多