use case-switch in c#

我的梦境 提交于 2019-12-11 16:58:40

问题


    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;
        }
    }

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));

        }
    }

I got the error at this

case icon.Title = "Fan"; it said cannot convert type String to 'ClickableGrid.Icon'


回答1:


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;
}

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;
}



回答2:


Switch/Case will check equality between the switch obj and the following statement of each case. In this example, your code will check equality between Icon and "Fan". Btw 'Icon.Title = "Fan" ' is an affectation, not a bool expression. Try something like switch (Icon.Title), and case "Fan".

Sry for bad writing, i'm french and on phone.

Good luck,




回答3:


You need to switch on a primitive value, i.e. string or int. For example, change your code to:

    var title = icon.Title;
    switch (title)
    {
      case "Fan":
          Console.WriteLine("Fan");
          break;
      case "TV":
          Console.WriteLine("TV);
          break;
      default:
          Console.WriteLine("Default case");
          break;

    }



回答4:


switch icon.Title
           Case "Fan"

This is what you are trying to do. However, this is somewhat a bad design. The code would be harder to maintain and debug.

I would suggest creating a dictionary with icon titles as keys and frame types as values. Then you could ditch using switch at all.

I would also suggest researching strategy pattern.




回答5:


In a switch/case, the computer will do a equality check. Only very specific types are allowed for this, as only with them equality is somewhat know. Also equality checks tend to be a somewhat tricky area of .NET: http://www.codeproject.com/Articles/18714/Comparing-Values-for-Equality-in-NET-Identity-and

C# version 7 drastically expanded the abilities of switch/case via Pattern Matching. Now the value of a case can be a complex expression.

However if you have a case where the Nr. of elements is dynamic, usually you should be using a Dictionary or similar collection instead of a switch/case. Indeed you will most likely fill the GUI (often a ComboBox) from the collection itself, using their key/value pairs. So mapping it back is easy.




回答6:


You can use switch only with primitives types (string, numbers, enumeration, char). If you want to check only Title then you should use the following

switch (icon.Title)
{
    case "Fan":
        Frame.Navigate(typeof(FanDetail));
        break;
    default:
        break;
}

If you want to check other properties of the object also, then you should use if-else statement

if(icon.Title == "Fan")
{
    Frame.Navigate(typeof(FanDetail));
}
else if(icon.IconId == 3)
{
    //Do something
}


来源:https://stackoverflow.com/questions/48181585/use-case-switch-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!