c# - 使用反射创建枚举

标签 c# reflection enums runtime

C# 是否提供了一种使用反射从头开始创建Enum 类型的方法?

假设,我有一组字符串:{"Single", "Married", "Divorced"} 并且我愿意构建以下枚举类型在运行时:

enum PersonStatus
{
    Single, Married, Divorced
}

这有可能吗?

最佳答案

不是没有做一些非常粗糙的事情,比如使用 Emit 生成程序集。无论如何,您将如何使用这样的枚举?这里的真正目标是什么?

编辑:既然我们知道你真正想做什么,this page建议您可以使用如下代码实现您的目标:

private void listViewComplex_CellEditStarting(object sender, CellEditEventArgs e)
{
    // Ignore edit events for other columns
    if (e.Column != this.columnThatYouWantToEdit)
        return;

    ComboBox cb = new ComboBox();
    cb.Bounds = e.CellBounds;
    cb.Font = ((ObjectListView)sender).Font;
    cb.DropDownStyle = ComboBoxStyle.DropDownList;
    cb.Items.AddRange(new String[] { "Single", "Married", "Divorced" });
    cb.SelectedIndex = 0; // should select the entry that reflects the current value
    e.Control = cb;
}

关于c# - 使用反射创建枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8979179/

相关文章:

c# - 支持新 CSS3 功能的自定义 Web 浏览器控件

c# - 如何测试C#传真程序?

java - 如何解决 InaccessibleObjectException ("Unable to make {member} accessible: module {A} does not ' opens {package }' to {B}") on Java 9?

c# - 数据绑定(bind)错误

java - 创建 DRY 枚举

c# - Graphics.DrawIcon 忽略比例变换?

c# - 带项目符号的 RTF 列表在第一行的缩进方式不同

c# - 为什么我无法从其他程序集中加载类?

ios - 使用枚举检查字符串

.net - 如何用给定枚举中的所有项目填充XAML中的WPF组合框?