通过类及其后代检索枚举

时间:2012-12-07 16:15:03

标签: c#-4.0 reflection

我有一个我已经定义的课程,我有很多从它派生的子课程。父类有一个枚举(让我们称之为' Barf')。每个后代ALSO都有一个具有相同名称但不具有相同值的枚举。我试图弄清楚如何做的是在祖先类中编写一个方法,该方法获取实例化对象的实际类的Barf版本。因此,如果我创建一个Ancestor实例,我想让这个方法处理Ancestor.Barf的条目。如果我创建一个祖先子类的实例,我想让方法处理Childx.Barf值。

显然这将是一个反射解决方案,但我的反思技巧非常稀少。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

只是为了它的乐趣,这是一种可能的方法:

public class Ancestor {
    public enum Caffeine {
        Tea,
        Coffee
    }

    public void ProcessValues() {
        var type = GetType();
        var nestedEnums = from t in type.GetNestedTypes()
                          where t.IsEnum
                          select t;
        var nestedEnum = nestedEnums.Single();
        foreach(var val in Enum.GetValues(nestedEnum)) {
            Console.WriteLine("Drinking {0}", val);
        }
    }
}

public class Descendant : Ancestor {
    public new enum Caffeine {
        Jolt,
        RedBull
    }
}

// The following prints:
// Drinking Jolt
// Drinking RedBull
Ancestor x = new Descendant();
x.ProcessValues();

当然,你可以使用多态来实现同样的目的:

public class Ancestor {
    public enum Caffeine {
        Tea,
        Coffee
    }

    protected virtual Type GetNestedEnum() {
        return typeof(Ancestor.Caffeine);
    }

    public void ProcessValues() {
        var nestedEnum = GetNestedEnum();

        foreach(var val in Enum.GetValues(nestedEnum)) {
            Console.WriteLine("Drinking {0}", val);
        }
    }
}

public class Descendant : Ancestor {
    public new enum Caffeine {
        Jolt,
        RedBull
    }

    protected override Type GetNestedEnum() {
        return typeof(Descendant.Caffeine);
    }
}

正如Justin Morgan所指出的那样,需要这样的结构可能表明代码中存在潜在的设计问题。