是否有可能从派生类中获取基类的枚举值而不使用反射?派生类的基类枚举值?
下面的代码使用反射,这似乎有点矫枉过正从对象实例中获取基类字段值。
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;
}
}
}
你想要访问什么?对于任何对象实例类型,Enum类型的所有属性及其相应的可能值?不清楚你想回答什么问题。 – jro 2009-09-24 21:08:42
是你的权利,一个对象实例的当前值。 – Ferdeen 2009-09-26 20:24:37