C#中的用例切换 [英] use case-switch in c#
本文介绍了C#中的用例切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Icon
{
public int IconID { get; set; }
public string Title { get; set; }
public string Room { get; set; }
public string ImageCover { get; set; }
}
public class IconManager
{
public static List<Icon> GetIcons()
{
var Icons = new List<Icon>();
Icons.Add(new Icon { IconID = 1, Title = "Fan", Room = "Enter-Room", ImageCover = "Assets/1.png" });
Icons.Add(new Icon { IconID = 2, Title = "AirConditioner", Room = "Enter-Room", ImageCover = "Assets/2.png" });
Icons.Add(new Icon { IconID = 3, Title = "WifiRouter", Room = "Enter-Room", ImageCover = "Assets/3.png" });
Icons.Add(new Icon { IconID = 4, Title = "Camera", Room = "Enter-Room", ImageCover = "Assets/4.png" });
Icons.Add(new Icon { IconID = 5, Title = "OfficePhone", Room = "Enter-Room", ImageCover = "Assets/5.png" });
Icons.Add(new Icon { IconID = 6, Title = "TV", Room = "Enter-Room", ImageCover = "Assets/6.png" });
Icons.Add(new Icon { IconID = 7, Title = "Clean", Room = "Enter-Room", ImageCover = "Assets/7.png" });
return Icons;
}
}
当我单击每个项目时,我将导航到该框架,但如何使用 switch case 执行此操作?这是我的 click_event
When I click each item i will navigate to that frame but how to do it with switch case ? here is my click_event
private void Grid_Clicked(object sender, ItemClickEventArgs e)
{
var icon = (Icon)e.ClickedItem;
IconResult.Text = "You selected a " + icon.Title;
var container = ForegroundElement.ContainerFromItem(e.ClickedItem) as GridViewItem;
if (container != null)
{
//find the image
var root = (FrameworkElement)container.ContentTemplateRoot;
var image = (UIElement)root.FindName("ConnectedElement");
//prepare the animation
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("Image", image);
}
switch (icon)
{
case icon.Title = "Fan";
Frame.Navigate(typeof(FanDetail));
}
}
我在这里遇到了错误
case icon.Title = "粉丝";它说不能将类型 String 转换为 'ClickableGrid.Icon'
case icon.Title = "Fan"; it said cannot convert type String to 'ClickableGrid.Icon'
推荐答案
不能以这种方式使用 C# switch
语句.您应该将其替换为 if
语句或使用新的 模式匹配功能在 C# 7 中引入:
You can't use C# switch
statement this way. You should replace it with a if
statement or use the new pattern matching feature introduced with C# 7:
switch (icon)
{
case Icon i when i.Title == "Fan":
{
Frame.Navigate( typeof(FanDetail) );
break;
}
default:
break;
}
但是,如果您拥有的唯一类型是 Icon
,您可以更简单地打开 Title
本身:
However, if the only type you have is an Icon
, you can more simply switch on the Title
itself:
switch (icon.Title)
{
case "Fan":
{
Frame.Navigate( typeof(FanDetail) );
break;
}
default:
break;
}
这篇关于C#中的用例切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文