是否可以在不使用反射的情况下从派生类获取基类的枚举值?
下面的代码使用反射,从对象实例中获取基类字段值似乎有点矫枉过正。
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;
}
}
}
请您参考如下方法:
因此,不太清楚您要查找的内容,因为 BaseClass 中实际上没有字段,只有枚举类型定义。以下任一项:
Enum.GetValues(typeof(BaseClass.eEnum));
或
Enum.GetValues(typeof(DerivedClassA.eEnum));
将为您提供枚举值。如果您在编译时不知道枚举的名称,那么反射是唯一的方法。
