jeudi 3 décembre 2020

C#: Cast object to satisfy "struct, Enum" generic constraint [duplicate]

I'm using reflection to get all the properties of an object, and if the property is an enum, I want to call a method in a library I don't own which has the constraint : struct, Enum.

The problem is I can't figure out how to cast the object I get back from GetValue() to something that will satisfy the method constraints. Obviously if I knew the specific enum type of the property I could cast to that, but all I know is it's some type of enum. Any ideas?

foreach (var prop in myObj.GetType().GetProperties())
{
    if (prop.PropertyType.IsEnum)
    {
        EnumMethod(prop.GetValue(myObj));
    }
}

void EnumMethod<T>(T val) where T : struct, Enum { /* ... */ }




Aucun commentaire:

Enregistrer un commentaire