简体   繁体   中英

Base Class Enum Value from Derived Class?

Is it possible to get the enum value of a base class, from a derived class, without using reflection ?

The code below using Reflection, which seems a bit of overkill to get a base class field value from an object instance.

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

So, not quite clear on exactly what you're looking for since there are really no fields in BaseClass, just the enum type definition. Either of these:

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

or

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

will give you the values of the enumeration. If you don't know the name of the enumeration at compile time, then reflection is the only way to go.

Your above code does not get a field value, but rather the type objects of all nested types.

The recursion in the method TraverseTheObjectHierachyForTheTaskListEnum is necessary, beacuse type.GetNestedTypes() will only return the types of the actual type provicded (that is DerivedClassA), but not of any types nested in its base classes.

You can easily verify this behaviour by stepping through your code with the debugger. You won't get any nested types for DerivedClassA , but for the base class type.GetNestedTypes() will return the enum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM