vendredi 29 mai 2020

Using a struct as advanced enum type and attempting to access the properties by index

I followed this guide on making a more complicated enum type for my implementation. http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

So far so good, however now I need to access the struct properties I have made ideally by index. A use case is if I get in a list of integers, I want to be able to provide a list of strings with the seasons in, e.g. {1,4,7} would get me {"Winter", "Spring", "Summer"} for example.

So in effect, using this example, I would like to be able to select Month where the index is 7 for example and get out the season of "Summer".

My first step was to get the names like so:

IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);

I then attempted to get the particular Month with:

foreach(string name in names) { 
  Month m = (Month) typeof(Month).GetType().GetProperties()
  .Single(info => info.Name == name)
  .GetValue(typeof(Month),null);
}

however this is going to cause me to iterate over the entire collection for every value I want to get.

Ultimately I think I'm headed in the wrong direction and would really appreciate a pointer. At the moment I'm trying to do this in a method in another class, but don't see why it couldn't be a getter in the struct itself, although that may be complicated given the binding attributes in use.





Aucun commentaire:

Enregistrer un commentaire