Creating an Enumeration Using Reflection

Does C# suggest creating an Enum type from scratch using reflection?

Suppose I have a set of strings : {"Single", "Married", "Divorced"} , and I'm ready to create the following type of enumeration at runtime:

 enum PersonStatus { Single, Married, Divorced } 

How is this possible?

+4
source share
2 answers

Do not get along with not very rough things, like creating assemblies using Emit. How would you use such a jumper? What is the real goal here?

EDIT: Now that we know what you really want to do, this page means that you can get your ideal goals using code like the following:

 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; } 
+8
source

Does C # offer a way to create an Enum type from scratch using reflection?

Yes it is possible. If you want to create types (including enumerations) at run time, you can use Reflection.Emit to emit the actual MSIL code.

Here's a concrete example on how to achieve this using the DefineEnum method.

+8
source

Source: https://habr.com/ru/post/1392554/


All Articles