返回基于选择枚举值 [英] return enum value based on selection

查看:120
本文介绍了返回基于选择枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举作为

 公共枚举操作
{
添加= 1,
。减去= 2,
乘= 3,
除法= 4
}

我有四个单选按钮:加,减,乘,除



根据的选择,我想回到相应的枚举值。我所有的单选按钮出现在一个组框。



我知道这是一个简单的事情,但很长一段时间,我无法得到它的权利。谢谢你。



修改



这就是我已经试过....

 公开操作操作
{
得到
{
的foreach(控制控制gbxOperation.Controls)
{
无功单选=控制,单选按钮;
如果(单选= NULL&放大器;!&安培; radioButton.Checked)
{
如果(radioButton.Text.ToLower()==增加)
返回Operation.Add ;
如果(radioButton.Text.ToLower()==减)
返回Operation.Substract;
如果(radioButton.Text.ToLower()==正片叠底)
返回Operation.Multiply;
如果(radioButton.Text.ToLower()==鸿沟)
返回Operation.Divide;
}
}
返回Operation.Add;
}
}


解决方案

这是不是很从你的问题清楚,但如果你有一个像串添加,并且希望将其转换为工作,您可以使用 Enum.Parse() 。是这样的:

 操作op =(操作)Enum.Parse(typeof运算(操作),S); 



不过,可能是一个更好的选择是单选按钮与枚举值直接,不通过关联按钮的文字。究竟是如何做到这一点您使用要看是什么样的UI库。


I have a enum as

public enum Operation
{
    Add = 1,
    Substract = 2,
    Multiply = 3,
    Divide = 4
}

I have four radio buttons : Add, Subtract, Multiply, Divide.

Based on the selection, I want to return the corresponding Enum value. All my radio buttons are present in a groupbox.

I know this is a simple thing, but from long time I am not able to get it right. Thanks.

EDIT

Thats what I have tried....

    public Operation Operation
    {
        get
        {
            foreach (Control control in gbxOperation.Controls)
            {
                var radioButton = control as radioButton;
                if (radioButton != null && radioButton.Checked)
                {
                    if(radioButton.Text.ToLower() == "add")
                        return Operation.Add;
                    if (radioButton.Text.ToLower() == "subtract")
                        return Operation.Substract;
                    if (radioButton.Text.ToLower() == "multiply")
                        return Operation.Multiply;
                    if (radioButton.Text.ToLower() == "divide")
                        return Operation.Divide;
                }
            }
            return Operation.Add;
        }
    }

解决方案

It's not very clear from your question, but if you have a string like "Add" and you want to convert it to Operation, you can use Enum.Parse(). Something like:

Operation op = (Operation)Enum.Parse(typeof(Operation), s);

But probably a better option would be to associate the radio buttons with the enum values directly, not through the text of the button. How exactly to do that depends on what kind UI library are you using.

这篇关于返回基于选择枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆