【问题标题】:Is it possible to use a method as the first parameter to an extension method?是否可以使用方法作为扩展方法的第一个参数?
【发布时间】:2016-03-22 19:55:50
【问题描述】:

我尝试过这样做:

public static EventHandler ToEventHandler(this Action callback)
{...}

当我想将像 void x() 这样的简单方法传递给为 EventHandler 键入的方法时,对于一些语法糖。

但是当我尝试这样称呼它时:

SomeMethod(x.ToEventHandler());

我得到一个编译器错误:

x() is a 'method', which is not valid in the given context  

由于方法是 .NET 中的一等公民,我不明白为什么这是不可能的。为什么不喜欢这样,还有其他方法可以完成我想要做的事情吗?

【问题讨论】:

标签: c# extension-methods


【解决方案1】:

你不能这样做,因为x 是一个方法,并且编译器在使用扩展方法时不会神奇地将方法通过其标识符转换为委托(我相信它确实应该能够这样做.. .).

你需要的是这个:SomeMethod(new Action(x).ToEventHandler());

另一方面,EventHandler 有两个输入参数,而您希望使用 Action(无参数委托...)。我怀疑您正在尝试这样做:

EventHandler handler = (sender, e) => callback();

...然后,如果您要走这条路,那很好。

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2017-06-15
    • 2020-09-20
    • 2015-06-11
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多