【问题标题】:Lambda Error in Nancy Sample ApplicationNancy 示例应用程序中的 Lambda 错误
【发布时间】:2016-04-29 12:51:45
【问题描述】:

在尝试让简单的 Nancy 示例程序运行时收到的错误让我有些困惑。

namespace NancyServer {

    using Nancy;

    public class ServerApi : NancyModule {
        public ServerApi() {
            Get["/"] = _ => "Hello World";
        }
    }

}

Visual Studio 2013 pro 在我的路径中对 lambda 犹豫不决。

_ => "Hello World";

我也尝试了一些其他的表达方式,它们都有同样的问题。

Get["/products/{id}"] = _ => {
    System.Console.WriteLine( "test" );
};

上面的 sn-p 也是直接从 Nancy wiki 拉出来的。

Intellisense 强调了 lambda 赋值 _ => 并表示委托不接受一个参数。如果我尝试构建,则会出现三个错误。

Error 1 Delegate 'System.Func<dynamic,System.Threading.CancellationToken,System.Threading.Tasks.Task<dynamic>>' does not take 1 arguments
Error 2 Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<dynamic>'
Error 3 Cannot convert lambda expression to delegate type 'System.Func<dynamic,System.Threading.CancellationToken,System.Threading.Tasks.Task<dynamic>>' because some of the return types in the block are not implicitly convertible to the delegate return type

我已经用谷歌搜索了几个小时,但无法弄清楚这里发生了什么。这是环境错误吗?可能存在某种命名空间问题吗?我已将 Nancy 和 Nancy.Hosting.Self 作为依赖项添加到我的项目中。项目中唯一的其他代码是自托管服务的简单主代码。

namespace NancyServer {

    using System;
    using Nancy.Hosting.Self;

    public class ServerMain {
        static void Main( string[] args ) {
            var nancyHost = new NancyHost( new Uri( "http://localhost:25000" ) );
            nancyHost.Start();
            Console.WriteLine( "Server running..." );
            Console.ReadKey();
            nancyHost.Stop();
        }
    }

}

我在VS2013 pro中直接通过Nuget添加了Nancy和Nancy.Hosting.Self。

【问题讨论】:

    标签: c# rest lambda compiler-errors nancy


    【解决方案1】:

    像这样改变它: Get["/"] = (params,token) =&gt; Task.FromResult&lt;dynamic&gt;("Hello World");

    Nancy v2.0.0 现在一直是异步的。

    【讨论】:

    • 澄清一下,第二个参数是CancellationToken
    • Nancy 2.0.0 是预发布 alpha,您可能需要在学习时考虑使用最新的稳定版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多