I am trying to use reflection to list the public members and methods of a few classes in various projects inside of one Visual Studio开发者_StackOverflow中文版 solution. All of the classes I am trying to access are C# and they are all being accessed from a C# class. The code I'm using to make these calls is as follows:
public void PopulateEventParamTree()
{
System.Console.WriteLine(source.GetType().ToString());
Type type = (Type)source.getEventType();
System.Console.WriteLine(type.ToString());
foreach (MemberInfo member in type.GetMembers())
{
System.Console.WriteLine("\t" + member.ToString());
}
}
Most of the outputs work fine (i.e. Int32, Double, System.String). My problem is that when I try to list enums I get an output to the console that looks like this:
Namespace.Subspace.event+EVENT_TYPE
I would like to be able to see all of the inner values of the enum instead of just its name. For example, the enum
public enum EVENT_TYPE
{
EVENTDOWN,
EVENTMOVE,
EVENTUP,
}
should output something like this
Namespace.Subspace.class+EVENT_TYPE EVENTDOWN
Namespace.Subspace.class+EVENT_TYPE EVENTMOVE
Namespace.Subspace.class+EVENT_TYPE EVENTUP
Any help that anyone can provide would be greatly appreciated. I've exhausted everything I've been able to find thus far but a fresh perspective would be nice.
Thanks
Use System.Enum.GetNames(typeof(EVENT_TYPE))
.
you will probably have to deal this special case (not using reflection for enums).
how to get enum and values via reflection
var importAssembly = System.Reflection.Assembly.LoadFile("test.dll");
Type[] types = importAssembly.GetTypes();
foreach (Type type in types)
{
if (type.IsEnum)
{
var enumName=type.Name;
foreach (var fieldInfo in type.GetFields())
{
if (fieldInfo.FieldType.IsEnum)
{
var fName=fieldInfo.Name;
var fValue=fieldInfo.GetRawConstantValue();
}
}
}
}
So in your case checking if source is an enum type and then calling GetEnumNames() would allow the code to act on classes, enums etc.
private void Work()
{
var type = typeof(numbers);
string [] members;
if(type.IsEnum)
members = typeof(numbers).GetEnumNames();
}
public enum numbers
{
one,
two,
three,
}
The enums are implemented as public static readonly fields (probably also const); your current code should work... You just need to get the name from the FieldInfo. And call GetValue if you want the value.
However, Enum.GetValues(type) is easier...
There is a way to call in few lines
public enum TestEnum // in some assembly there is some enum
{
A = 0,
B,
C
}
And then this
var assembly = Assembly.Load("TestCS");
var converter = new EnumConverter(assembly.GetType("TestCS.TestEnum"));
var enumValColl = converter.GetStandardValues();
foreach (var val in enumValColl)
Debug.WriteLine("{0} = {1}", val, (int)val);
Output
A = 0
B = 1
C = 2
精彩评论