samedi 6 juin 2015

Using reflection to get attribute names in struct returns value__

I want to populate a combo box with all of the available item types in my struct ItemTypes:

public enum ItemTypes
{
    Ore,
    Ice,
    Mineral,
    Pi
}

In order not to add a new item type in 2 places if I do have to add one eventually (not likely, but still could happen), I want to use reflection to populate that combo box instead of manually adding each item type in a list. This is how I do it:

private void InitItemTypeComboBox()
{
    ComboBoxItemTypes = new List<String>();

    foreach (var itemType in typeof(EveItem.ItemTypes).GetFields())
    {
        ComboBoxItemTypes.Add(itemType.Name);
    }

    SelectedComboBoxItemType = ComboBoxItemTypes.ElementAt(0);
}

Unfortunately, the GetFields() and itemType.Name functions return not only the 4 item types in my struct, it also returns value__ as first field, so I have an extra element in my combo box that I do not want.

I have tried using the BindingFlags.DeclaredOnly, BindingFlags.Public and BindingFlags.Instance flags of the GetFields() together, but it still returns that first value__ element that I don't want.

Is there a way to specify that I do not want this element other than by manually skipping the first element returned by typeof(EveItem.ItemTypes).GetFields()?

EDIT:

If it changes anything, my ItemTypes struct is nested inside another one of my public classes.





Aucun commentaire:

Enregistrer un commentaire