mercredi 16 septembre 2015

C#: Get enum type using reflection (not the underlying type)

Assuming the following enum:

public enum Gender
{
    NotSet,
    Masculine,
    Feminine,
    Neuter,
    Other
}

And the following stripped down class:

public class Term
{
    public Gender Gender { get; set; }
    ...
    // Other properties (including other enums)
}

I wish to set Term.Gender using Reflection, ensuring that the value is defined on Gender before doing so.

I've tried

PropertyInfo pi = typeof(Term).GetProperty("Gender", BindingFlags.Public | BindingFlags.Instance);

pi.PropertyType then returns {Int32 Gender}.

If I then use

Enum.IsDefined(pi.PropertyType, aStringValue)

.NET throws an exception saying "Type provided must be an Enum".

I think the problem here is that the PropertyInfo obtains the underlying type and therefore states that the property is an Int32 rather than Gender.

I am able to call

pi.SetValue(mytermObj, aValue)

but this provides no safety that aValue is defined on Gender.

How can I dynamically, safely set an enum property if I know the name of that property and a corresponding value?





Aucun commentaire:

Enregistrer un commentaire