vb.net 带有 Razor 和 .NET 的一行 If 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18341930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:44:36  来源:igfitidea点击:

One line If statement with Razor and .NET

asp.net-mvcvb.netrazorif-statement

提问by ElliotSchmelliot

Razor doesn't seem to like my one line Ifstatements... Normally in VB.NET, I can write a one line Ifstatement like so:

Razor 似乎不喜欢我的单行If语句……通常在 VB.NET 中,我可以If像这样编写单行语句:

If True Then Dim x As Integer

However, when I do the same with Razor in a .vbhtmlfile like this...

但是,当我在这样的.vbhtml文件中对 Razor 执行相同操作时...

@If True Then Dim x As Integer

I get the error

我收到错误

The "If" block was not terminated. All "If" statements must be terminated with a matching "End If".

“If”块没有终止。所有“If”语句都必须以匹配的“End If”结束

What gives? Why won't Razor take this? I realize that a simple solution is to just use a code block like

是什么赋予了?为什么 Razor 不接受这个?我意识到一个简单的解决方案是只使用像这样的代码块

@code
    If True Then Dim x As Integer
End Code

But thats not what I'm looking for. I'm curious why Razor can't recognize a VB.Net one line Ifstatement using just @If.... Any ideas?

但这不是我要找的。我很好奇为什么 Razor 不能If仅使用@If.... 有任何想法吗?

采纳答案by Joan Caron

Same problem with C#, As explained here:

用C#同样的问题,如解释在这里

Razor uses code syntax to infer indent: Razor Parser infers code ending by reading the opening and the closing characters or HTML elements. In consequence, the use of openings “{“ and closings “}” is mandatory, even for single line instructions

Razor 使用代码语法来推断缩进:Razor Parser 通过读取开始和结束字符或 HTML 元素来推断代码结束。因此,必须使用开头“{”和结尾“}”,即使是单行指令

You do the wright thing

你做正确的事

@code
    If True Then Dim x As Integer
End Code

You can do it like that but it's not you like (inline)

你可以那样做,但不是你喜欢的(内联)

@If (True) Then
    Dim x As Integer
End If

回答by jweaver

In VB.Net you do a inline If Statement like this:

在 VB.Net 中,您可以像这样执行内联 If 语句:

@(If(boolCondition, "truePart", "falsePart"))

回答by PeaceFrog

I'm not sure about VB, but this works in C#.

我不确定 VB,但这适用于 C#。

@{if (true) { int x; }}