这可能是一个愚蠢的问题,但是,我有一种方法可以使页面的语法更易于阅读
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 方法?
最佳答案
Lambda 是无类型的,因此这是不可能的。
如果您不关心方法参数(看起来确实如此),为什么不将方法签名更改为:
public void Do(Action method,
DispatcherPriority priority = DispatcherPriority.Normal)
然后,第二个示例将正常工作,因为编译器将能够将 lambda 隐式转换为 Action
。
如果您确实想接受委托(delegate)不带参数的方法的任何委托(delegate)类型的实例,则必须坚持使用当前拥有的东西。
关于c# - 逆变参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4489414/