如何将 Func<> 属性/方法传递给 NancyFx Get() 方法?

NancyFx (2.x)NancyModule.Get()方法定义为:


public virtual void Get(string path, Func<dynamic, object> action, [Func<NancyContext, bool> condition = null], [string name = null]);

正常用法是:


public class MyModule

{

    public MyModule() 

    {

        this.Get("/", parameters => {

            this.RequestHandler = new RequestHandler();


            return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);

        });

    }

}

我想将第二个参数定义为一个属性,以便我可以用于多个路径,如下所示:


public class MyModule

{

    Func<dynamic, object> indexHandler = parameters => {

        // Error: Keyword "this" is not available in this context

        this.RequestHandler = new RequestHandler();


        // Error: Keyword "this" is not available in this context

        return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);

    };


    public MyModule() 

    {

        this.Get("/", indexHandler);

        this.Get("/index", indexHandler);

    }

}

如果我这样做,它会起作用:


public class MyModule

{

    public MyModule() 

    {

        Func<dynamic, object> indexHandler = parameters => {

            this.RequestHandler = new RequestHandler();


            return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);

        };


        this.Get("/", indexHandler);

        this.Get("/index", indexHandler);

    }

}

但我不想在构造函数中定义它。我究竟做错了什么?有没有其他方法可以做到这一点?


白猪掌柜的
浏览 161回答 2
2回答

白板的微信

这应该有效:public class MyModule{&nbsp; &nbsp; public MyModule()&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;this.Get("/", IndexHandler);&nbsp; &nbsp; &nbsp; &nbsp;this.Get("/index", IndexHandler);&nbsp; &nbsp; }&nbsp; &nbsp; private object IndexHandler(dynamic parameters) {&nbsp; &nbsp; &nbsp; &nbsp; this.RequestHandler = new RequestHandler();&nbsp; &nbsp; &nbsp; &nbsp; return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);&nbsp; &nbsp; }}

温温酱

安德鲁的回答是有效的,应该已经足够了,但显然(在您的 MVCE 中)该方法定义不存在。这是正确的定义(至少是 VS 想要的):public virtual void Get(string path, Func<object, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)幸运的HandleRequest是,您是可等待的,因此您只需要编辑返回类型。这是正确的定义:private Task<object> IndexHandler(dynamic parameters){&nbsp; &nbsp; this.RequestHandler = new RequestHandler();&nbsp; &nbsp; var someOtherInfo = "";&nbsp; &nbsp; return this.RequestHandler.HandleRequest("/", parameters, someOtherInfo);}希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP