C# - 开关枚举 - 类型名称 ' '类型中不存在 ' '
在 switch case 中使用它时,出现错误“类型名称“Home”在类型“MenuEnum”中不存在”。如果我只是使用 if 语句,它就可以正常工作。
问题是当我使用 MenuEnum.Home 时,我收到 IDE 错误,并且我的代码无法编译。
我还在下面的代码示例中切换到常规 switch 语句。
在下面添加代码
public void Selected(MenuEventArgs<MenuItem> args)
{
//The ULR to navigate to
var url = string.Empty;
try
{
//If there is no data do nothing
if(string.IsNullOrEmpty(args.Item.Text))
return;
//switch on the incoming text
switch (args.Item.Text)
{
//IDE Error on home (will not compile)...
case MenuEnum.Home.ToString():
url = "/";
break;
default:
url = "";
break;
}
//working code
if (args.Item.Text == MenuEnum.Home.ToString().Replace('_', ' '))
{
url = "/";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Navigation.NavigateTo(url);
}
/-枚举文件-/
namespace ManagerDashboard2022.Client.ENUMs;
/// <summary>
/// The Items in the menu
/// </summary>
public enum MenuEnum
{
Home
}
I am getting an error "The type name 'Home' does not exist in the type 'MenuEnum'" when using it in a switch case. If I just go a if statement it works without issue.
The issue is when I use the MenuEnum.Home I am getting a IDE error and my code will not compile.
I also switched to a regular switch statement below in the code example.
Added Code below
public void Selected(MenuEventArgs<MenuItem> args)
{
//The ULR to navigate to
var url = string.Empty;
try
{
//If there is no data do nothing
if(string.IsNullOrEmpty(args.Item.Text))
return;
//switch on the incoming text
switch (args.Item.Text)
{
//IDE Error on home (will not compile)...
case MenuEnum.Home.ToString():
url = "/";
break;
default:
url = "";
break;
}
//working code
if (args.Item.Text == MenuEnum.Home.ToString().Replace('_', ' '))
{
url = "/";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Navigation.NavigateTo(url);
}
/-Enum file-/
namespace ManagerDashboard2022.Client.ENUMs;
/// <summary>
/// The Items in the menu
/// </summary>
public enum MenuEnum
{
Home
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确实想打开字符串值,则可以将其替换
为
nameof
在编译时求值以生成字符串常量“Home”(在本例中)。由于这是一个常量,因此您可以“切换”它。使用 nameof 而不是仅使用字符串“Home”的优点是,使用 nameof 时,MenuEnum.Home 值需要存在 - 因此您会因拼写错误而出现编译器错误。
您收到的错误消息是:
并不是很有帮助。它应该是(IMO)类似于“你不能将运行时表达式作为 case 标签”。
If you really want to switch on string values, you can replace that
with
nameof
is evaluated at compile time to result in the string constant "Home" (in this case). As this is a constant, you can "switch" on it.The advantage of using nameof instead of just the string "Home" is that with nameof the MenuEnum.Home value needs to exist - so you get an compiler error on typos.
That error message you got:
is not very helpful in this case. It should have been (IMO) something like "you cannot have a runtime expression as case label".
谢谢你@cly。
我需要解析枚举并打开返回的项目
Thank you @cly.
I needed to parse the enum and switch on that returned item