1

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

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

4

1 回答 1

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 所指出的那样,需要这种构造可能表明您的代码中存在潜在的设计问题。

于 2012-12-08T01:11:53.530 回答