mercredi 21 janvier 2015

Function returning object array of runtime determined enum types

So I have a bunch of enum types (much more than this)



public enum Lobes
{
Unspecified,
Frontal,
Parietal,
Temporal,
Occipital,
Hemispheric
}
public enum Predominantly
{
Unspecified,
Frontal,
Midline,
Occipital
}
public enum Asymmetric
{
Unspecified,
Unilateral,
Bilateral
}


and I am storing the specified values as a dict:



[DataMember]
public Dictionary<string, int> Modifiers { get; private set; }
public void SetModifiers(params object[] aEnums)
{
foreach (object aEnum in aEnums)
{
string myKey = aEnum.GetType().Name;
int myValue = Convert.ToInt32(aEnum);

if (Modifiers.ContainsKey(myKey))
{
Modifiers[myKey] = myValue;
}
else
{
Modifiers.Add(myKey, myValue);
}
}
}


So far so good I guess. Now I want to create a function that returns an object array of the relevant enums. I'm guessing I have to use reflection, I've been reading a few answers on that but I'm a bit confused. So far I've tried:



public object[] GetModifiers()
{
object[] returnObjects = new object[Modifiers.Count()];

int i = 0;
string nameSpaceOfAEnums = "Namespace.Is.Good";
foreach (KeyValuePair<string, int> pair in Modifiers)
{
string enumName = nameSpaceOfAEnums + pair.Key;
// Doesn't work
// returnObjects[i] = (Type.GetType(enumName))pair.Value;

// would work if I go through all the different enums one by one:
returnObjects[i] = (Lobes) pair.Value;

i++;
}

return returnObjects;
}


Now, obviously, since I'm lazy, I don't really want a giant if-else if-else if soup checking for all the different enum types. Is it possible to achieve with reflection what I'm trying to do in this line:



returnObjects[i] = (Type.GetType(enumName))pair.Value;





Aucun commentaire:

Enregistrer un commentaire