函数返回运行时的对象数组确定了枚举类型

时间:2015-01-21 14:26:23

标签: c# reflection

所以我有一堆枚举类型(远不止于此)

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

我将指定的值存储为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);
            }
        }
    }

到目前为止我觉得这么好。现在我想创建一个返回相关枚举的对象数组的函数。我猜我必须使用反射,我一直在阅读几个答案,但我有点困惑。到目前为止,我已经尝试过:

    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;
    }

现在,显然,因为我很懒,我真的不想要一个巨大的if-else if-else如果汤检查所有不同的枚举类型。是否有可能通过反思实现我在这一行中要做的事情:

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

1 个答案:

答案 0 :(得分:1)

您可以使用Enum.ToObject

var type = (Type.GetType(enumName);
returnObjects[i] = Enum.ToObject(type, pair.Value);