My C# class MyClass (below) has members a, b, c, d, e, and f.
I'd like to use reflection to obtain a list of the data types of those members; for example (borrowing from Python notation): [ char[], ushort, char, byte, uint, ulong ].
class MyClass
{
public char [ ] a ;
public ushort b ;
public char c ;
public byte d ;
public uint e ;
public ulong f ;
}
class MainClass
{
public static void Main ( string [] args )
{
// get an array (or some kind of list) of MyClass' fields' data types ...
// for example: { char[], ushort, char, byte, uint, ulong }
// I've tried the following, but can't get a column of just the data types, alone ...
MemberInfo[] theMemberInfoArray = typeof(MyClass).GetMembers() ;
foreach (MemberInfo mi in theMemberInfoArray)
if (mi.MemberType == MemberTypes.Field)
Console.WriteLine ( "<" + mi.MemberType + ">\t"
+ "<" + mi.GetType() + ">\t"
+ "<" + mi.Name + ">\t" + mi ) ;
}
}
Program output appears as below:
<Field> <System.Reflection.RtFieldInfo> <a> Char[] a
<Field> <System.Reflection.RtFieldInfo> <b> UInt16 b
<Field> <System.Reflection.RtFieldInfo> <c> Char c
<Field> <System.Reflection.RtFieldInfo> <d> Byte d
<Field> <System.Reflection.RtFieldInfo> <e> UInt32 e
<Field> <System.Reflection.RtFieldInfo> <f> UInt64 f
I would like program output to appear as:
<Field> <System.Reflection.RtFieldInfo> <a> <Char[]> Char[] a
<Field> <System.Reflection.RtFieldInfo> <b> <UInt16> UInt16 b
<Field> <System.Reflection.RtFieldInfo> <c> <Char> Char c
<Field> <System.Reflection.RtFieldInfo> <d> <Byte> Byte d
<Field> <System.Reflection.RtFieldInfo> <e> <UInt32> UInt32 e
<Field> <System.Reflection.RtFieldInfo> <f> <UInt64> UInt64 f
this is how I did it, you want the FieldType which actually returns a Type instance.
This is the output:
You're looking for the Name property off of FieldType, which is available via FieldInfo. You'll need to cast MemberInfo to a FieldInfo first:
Output:
mi.Name is bringing back want you want, you jsut need to change your COnsole.WriteLine to print it again
I'm not sure that MemberInfo has the information you want. You might want to look at
GetFields()
and theFieldInfo
class, orGetProperties()
and thePropertyInfo
class.GetMembers()
returns all fields, properties and methods, so if your class contained these they would be enumerated as well.