2009-09-24 111 views
1

是否有可能从派生类中获取基类的枚举值而不使用反射?派生类的基类枚举值?

下面的代码使用反射,这似乎有点矫枉过正从对象实例中获取基类字段值。

using System; 

namespace Seans 
{ 
    public class BaseClass 
    { 
     public enum eEnum{a, b, c} 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      DerivedClassA newObject = new DerivedClassA(); 
      TraverseTheObjectHierachyForTheTaskListEnum(newObject.GetType()); 

      Console.ReadLine(); 
     } 

     public static Type GetTaskListType(Type type) 
     { 
      // Handle the cases where our enums are defined in the base class 
      return TraverseTheObjectHierachyForTheTaskListEnum(type); 
     } 

     private static Type TraverseTheObjectHierachyForTheTaskListEnum(Type type) 
     { 
      foreach (Type nestedType in type.GetNestedTypes()) 
      { 
       if (nestedType.IsEnum) 
       { 
        // Enum Name, now you can get the enum values... 
        Console.WriteLine(nestedType.FullName); 
        return nestedType; 
       } 
      } 

      if (type.BaseType != null) 
      { 
       return TraverseTheObjectHierachyForTheTaskListEnum(type.BaseType); 
      } 
      return null; 
     } 
    } 
} 
+0

你想要访问什么?对于任何对象实例类型,Enum类型的所有属性及其相应的可能值?不清楚你想回答什么问题。 – jro 2009-09-24 21:08:42

+0

是你的权利,一个对象实例的当前值。 – Ferdeen 2009-09-26 20:24:37

回答

3

所以,不完全清楚你正在寻找什么,因为在BaseClass中确实没有字段,只是枚举类型定义。无论是这些:

Enum.GetValues(typeof(BaseClass.eEnum)); 

Enum.GetValues(typeof(DerivedClassA.eEnum)); 

会给你列举的值。如果您在编译时不知道枚举的名称,那么反射是唯一的方法。

0

你上面的代码没有得到一个字段值,而是所有嵌套类型的类型对象。

方法TraverseTheObjectHierachyForTheTaskListEnum中的递归是必要的,因为type.GetNestedTypes()将只返回实际类型的provicded(即DerivedClassA)类型,但不包含嵌套在其基类中的任何类型。

通过使用调试器逐步执行代码,可以轻松验证此行为。你不会得到DerivedClassA的任何嵌套类型,但基类type.GetNestedTypes()将返回枚举。