【问题标题】:C# - ; expected in Throw New Excepction error using AssertC# - ;预计使用 Assert 引发新异常错误
【发布时间】:2018-01-13 13:07:39
【问题描述】:

我在 C# 项目中使用此代码

public async Task should_not_raise_exception(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
    {
        // given
        var connectionInfo = new ConnectionInformation
        {
            WebSocket = webSocket.Object
        };
        await slackConnection.Initialise(connectionInfo);

        var inboundMessage = new ChatMessage
        {
            MessageType = MessageType.Message,
            User = "lalala"
        };

        slackConnection.OnMessageReceived += message => throw new Exception("EMPORER OF THE WORLD");

        // when & then
        Assert.DoesNotThrow(() => webSocket.Raise(x => x.OnMessage += null, null, inboundMessage));
    }

但是当我编译它时,这向我显示了一个关于 ; 的错误。预期,关于错误的代码部分是这样的:

slackConnection.OnMessageReceived += message => throw new Exception("EMPORER OF THE WORLD");

        // when & then
        Assert.DoesNotThrow(() => webSocket.Raise(x => x.OnMessage += null, null, inboundMessage));

我正在使用框架 4.6.1

查看附件图片

【问题讨论】:

    标签: c# exception visual-studio-2015 frameworks throw


    【解决方案1】:

    只需这行代码即可重现问题:

    Action<string> foo = message => throw new Exception();
    

    问题在于,在 C# 7.0 之前,您不能单独使用 throw 作为表达式...而这正是表达式体 lambda 表达式所必须具备的。

    该行代码在 C# 7 中有效,但在 C# 6 或更早版本中无效。您使用的框架版本无关紧要 - 您使用的 C# 编译器很重要。

    您可以改用语句 lambda(基本上是一个使用大括号的 lambda 表达式)来修复您的代码:

    slackConnection.OnMessageReceived +=
        message => { throw new Exception("EMPORER OF THE WORLD"); };
    

    ...或者您可以升级以使用 C# 7 :)(例如,通过更新到 VS 2017。)

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      相关资源
      最近更新 更多