简体   繁体   中英

How to cast Enum value as a constant c#

I have a enumerator that holds tabpage collection names. I would like to use tabControl.SelectedIndexChanged event to execute specific code based on the caption/name of the tabpage.

Is it possible to use a switch statement like:

private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
{
    var tc = (TabControl)sender;
    switch (tc.SelectedTab.Name)
    {
        case Enum.GetName(typeof(tabPages), 0):
            // This is table page 0 , name="interchanges"
            // set default values
            break;
        case Enum.GetName(typeof(tabPages), 1):
            // Do something else page=1,name="ShowContents"
            break;
    }
}

You should convert the string to the enum. And then switch this. Example:

    tabPages tab = (tabPages)Enum.Parse(typeof(tabPages),tc.SelectedTab.Name);
    switch (tab)
    {
        case tabPages.interchanges:
            // This is table page 0 , name="interchanges"
            // set default values
            break;
        case tabPages.Showcontents:
            // Do something else page=1,name="ShowContents"
            break;
    }

Edit: Made this example real quick:

using System;

public class Test
{
    public static void Main()
    {
        string text = "One";
        TestEnum test = (TestEnum)Enum.Parse(typeof(TestEnum), text);
        switch (test)
        {
            case TestEnum.One:
            Console.WriteLine("ONE!");
            break;
            case TestEnum.Two:
            Console.WriteLine("TWO!");
            break;
            case TestEnum.Three:
            Console.WriteLine("THREE!");
            break;
        }
    }

    public enum TestEnum
    {
        One,
        Two,
        Three
    }
}

Alternative suggestion, although possibly harder to maintain:

Attach a delegate to the 'Tag' of each page, and have your code simply invoke whichever delegate is on that page. Your code becomes:

var tc = (TabControl)sender;
Action action = tc.Tag as Action;
if (action != null)
    action();

Another possibility is having a static Dictionary<string, Action> myActions defined, and just calling

myActions[tabName]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM