【发布时间】:2009-07-09 14:04:35
【问题描述】:
我的 C# 类 MyClass(如下)有成员 a、b、c、d、e 和 f。
我想使用反射来获取这些成员的数据类型列表; 例如(借用 Python 表示法):[ 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 ) ;
}
}
程序输出如下:
<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
我希望程序输出显示为:
<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
【问题讨论】:
-
在您的帖子中,实际输出和您所说的希望输出是相同的。我假设您想要的不是您发布的内容,因此请编辑您的问题以澄清您想要的输出实际是什么。
-
您必须缩进四位以保持格式。我已经为你做了。顺便说一句,这叫做“反思”,而不是“内省”。
-
我不明白这两个输出之间的区别。所需的输出只是重复没有尖括号的第 4 列。
标签: c# reflection types field