假设我有一个c#中的RadioButtonList。这个列表包含一个最喜欢的水果选择器(按字母顺序排序):
Favorite Fruits:
( ) Apple
( ) Banana
( ) Pineapple
( ) Pomegranate
…假设我有一个方法,可以在点击按钮时打印出关于你最喜欢的水果的事实:
private void FruitFactsButton_OnClick(arguments){
switch( favoriteFruits.SelectedIndex ){
case 0: // Apple
doStuffForApple();
break;
case 1: // Banana
doStuffForBanana();
break;
case 2: // Pineapple
doStuffForPineapple();
break;
case 3: // Pomegranate
doStuffForPomegranate();
break;
}
}
假设在我的代码库中有几十个开关/案例依赖于选择哪个favoriteFruits
元素。
如果我决定在这个列表中添加一个元素(不是在末尾),我必须手动找到每个开关/案例并更新索引(添加Banana
将迫使我+1 Kiwi
, Pineapple
和Pomegranate
的索引,如果我想保持所有字母顺序。)
是否有一种方法可以引用索引作为枚举值?就像,我能做一些类似的事情吗?
switch( favoriteFruits.SelectedIndex ){
case favoriteFruits.getEnumConstants.APPLE:
doStuffForApple();
break;
我知道有一个RadioButtonList.Items
访问器,但我被难住了,从那里去哪里。任何帮助都是感激的!
是否有一种方法我可以引用索引作为枚举值?
从你的整个帖子来看,似乎"你需要知道什么被点击了,并据此采取行动"。如果你要针对索引或控件的值进行测试,这真的无关紧要。如果是这种情况,那么执行以下操作应该会有所帮助:
// declare the items, no need to set values
public enum FavoriteFruits {
Banana,
Apple, }
// bind the enum to the control
RadioButtonList1.DataSource = Enum.GetValues(typeof(FavoriteFruits));
RadioButtonList1.DataBind();
// this is needed because SelectedValue gives you a string...
var selectedValue = (FavoriteFruits)Enum.Parse(typeof(FavoriteFruits),
RadioButtonList1.SelectedValue, true);
//...then you can do a switch against your enum
switch (selectedValue )
{
case FavoriteFruits.Apple:
doStuffForApple();
break;
case FavoriteFruits.Banana:
doStuffForBanana();
break;
}
确保验证SelectedValue
,因为如果没有选择,它将抛出异常。
如果我理解正确的话,您会使用枚举吗?
enum Fruits{
Apple = 0,
Banana = 1,
Pineapple = 2,
Pomegranate = 3
};
switch( favoriteFruits.SelectedIndex ){
case Fruits.Apple:
doStuffForApple();
break;