我的 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
最佳答案
我就是这样做的,您需要实际返回 Type 实例的 FieldType。
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;
}
这是输出:
<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
关于c# - C# 中的反射——想要一个类字段的数据类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1104105/