[ACCEPTED]-Reflection in C# -- want a list of the data types of a class' fields-field
this is how I did it, you want the FieldType 2 which actually returns a Type instance.
var members = typeof(TestMe).GetFields().Select(m => new
{
Name = m.Name,
MemType = m.MemberType,
RtField = m.GetType(),
Type = m.FieldType
});
foreach (var item in members)
Console.WriteLine("<{0}> <{1}> <{2}> <{3}> {3} {2}", item.MemType, item.RtField, item.Name, item.Type, item.Type, item.Name);
public class TestMe
{
public string A;
public int B;
public byte C;
public decimal D;
}
This 1 is the output:
<Field> <System.Reflection.RtFieldInfo> <A> <System.String> System.String A
<Field> <System.Reflection.RtFieldInfo> <B> <System.Int32> System.Int32 B
<Field> <System.Reflection.RtFieldInfo> <C> <System.Byte> System.Byte C
<Field> <System.Reflection.RtFieldInfo> <D> <System.Decimal> System.Decimal D
I'm not sure that MemberInfo has the information 5 you want. You might want to look at GetFields()
and 4 the FieldInfo
class, or GetProperties()
and the PropertyInfo
class.
GetMembers()
returns 3 all fields, properties and methods, so if 2 your class contained these they would be 1 enumerated as well.
You're looking for the Name property off 2 of FieldType, which is available via FieldInfo. You'll 1 need to cast MemberInfo to a FieldInfo first:
foreach (MemberInfo mi in theMemberInfoArray)
{
if (mi.MemberType == MemberTypes.Field)
{
FieldInfo fi = mi as FieldInfo;
Console.WriteLine(fi.FieldType.Name);
}
}
Output:
Char[]
UInt16
Char
Byte
UInt32
UInt64
mi.Name is bringing back want you want, you 2 jsut need to change your COnsole.WriteLine 1 to print it again
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.