在运行时输入枚举

时间:2010-12-15 19:26:51

标签: c# dynamic parameters enums runtime

我有一个方法GenerateOutput,它打印一个字符串列表。该方法将多个枚举作为参数,并根据输入到方法中的标志输出结果。我知道枚举是为编译时设计的,但是可以根据用户在程序中选择的选项在运行时更改输出吗? 基本上,我有各种复选框,代表可能的枚举。当用户选择一个选项时,该标志应作为参数添加到GenerateOutput方法中。可以这样做吗?感谢

1 个答案:

答案 0 :(得分:3)

我认为您想要做的事情(我不确定我完全理解您的问题)是在运行时建立一个Enum值以传入函数。

假设您的枚举使用[flags]属性指定:

[flags]
public enum TestEnumerations
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 4,
    //etc
}

然后你可以这样做:

// In checkbox handlers, e.g.
tEnums |= TestEnumerations.Value1;

// Where you call the method
GenerateOutput(tEnums);

或者,正如Francisco在评论中所建议的那样,有一个List列表(如果你只希望每个枚举值出现一次,则为HashSet):

// In checkbox handlers, e.g.
list.Add(TestEnumerations.Value1);

// Where you call the method
GenerateOutput(list);
相关问题