简体   繁体   English

如何将枚举值转换为常量 c#

[英]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.我想使用tabControl.SelectedIndexChanged事件根据tabControl.SelectedIndexChanged的标题/名称执行特定代码。

Is it possible to use a switch statement like:是否可以使用 switch 语句,例如:

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另一种可能性是定义了一个静态Dictionary<string, Action> myActions ,然后调用

myActions[tabName]();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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