Cru*_*ids 2 .net c# blazor asp.net-blazor
我将用“我已经有了答案”作为这个问题的序言。但我怀疑其他人也遇到过类似的情况,我想分享我的解决方案。
问题:如何在 Balzor 中使用 switch 表达式来渲染组件?
我有一个场景,我有一个带有字符串属性的对象,并且我想根据字符串值呈现不同的按钮。使用 switch 语句,它看起来像这样
@switch(myObject.SomeStringValue)
{
case "StringValueOne": <ButtonComponent OnClick="@DoAThing"/> break;
case "StringValueTwo": <ButtonComponent OnClick="@DoTwoThing"/> break;
case "StringValueThree": <ButtonComponent OnClick="@DoThreeThing"/> break;
default: <ButtonComponent OnClick="@DoSomethingElse"/> break;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我想使用模式匹配在每种情况下匹配多个字符串值...
case is "StringValueOne" or "AnotherMatchingValue": <ButtonComponent OnClick="@DoAThing"/> break;
Run Code Online (Sandbox Code Playgroud)
根据 C# 文档,我找不到同时使用 switch 语句和模式匹配的方法。
现在,总的来说,我比 switch 语句更喜欢 switch 表达式的语法。我希望能够在 Blazor 中使用 switch 表达式来获得与上述 switch 语句类似的结果,该语句在 razor 文件中本机工作。我如何使用 switch 表达式来实现相同的目标?
好吧,这是一个答案,伙计们!
@(myObject.SomeStringValue switch
{
"StringValueOne" or "AnotherMatch" => (@<ButtonComponent OnClick="@DoAThing"/>),
"StringValueTwo" or "MatchTwo" => (@<ButtonComponent OnClick="@DoTwoThing"/>),
"StringValueThree" or "MatchThree" => (@<ButtonComponent OnClick="@DoThreeThing"/>),
_ => (@<ButtonComponent OnClick="@DoSomethingElse"/>)
})
Run Code Online (Sandbox Code Playgroud)
如果您找到其他方法来执行此操作或者这对您不起作用,请告诉我。
| 归档时间: |
|
| 查看次数: |
4364 次 |
| 最近记录: |