如何列出某类型的所有成员

如何列出某类型的所有成员

本示例使您可以列出给定数据类型的成员。列出类型成员的功能是快速发现哪些元素可用的很好方式。它是在系统中进行报告以及帮助开发用户文档的重要工具。使用 Reflection 命名空间,您可以控制希望显示给用户的成员类型以及其他信息(如特定方法的可见性)。还可以获取类中所有成员的信息,或仅指定某些子集(如方法或字段)。

 
C# ListMembers.aspx

[运行示例] | [查看源代码]

您可能想知道为何获取特定类型的信息很重要。毕竟,这就是帮助系统和帮助文档的用途,不是吗?下面的示例可以帮助您创建用户文档,或用于帮助动态调用方法或设置属性。

需要执行以下几个步骤。首先,需要获取用户希望使用的类型(以字符串的形式)。确定了要使用的类型后,需要分配一个对象来表示该类型。这将进行两项工作:创建后面步骤可以使用的对象,还确保指定类型存在并且可被系统找到。下面的示例向 System.String 类型分配一个对象。注意,尽管此处示例中通过“控制台”(Console) 对象向用户提供反馈,实际示例却将反馈发送给一个 ASP.NET 标签对象。但解释相同。

// don't forget your using statements at the top of your code...
Using System;
Using System.Reflection;

// class declaration, and method declaration...

// remember that this string is case-sensitive, so be careful
Type t = Type.GetType("System.String");

// check to see if we have a valid value. If our object is null, the type does not exist...
if (t == null) {
	// Don't assume that it is a SYSTEM datatype...
	Console.WriteLine("Please ensure you specify only valid types in the type field.");
	Console.WriteLine("REMEMBER: The Case matters (Byte is not the same as byte).");

	return; // don't continue processing
}
C# VB  

有了有效的类型对象以后,下一个问题是希望为类型检索什么类型的成员?是需要方法、静态方法还是实例字段?在 Reflection 命名空间中,有一组 Info 对象,每个对象表示您系统的一组不同成员。例如,有一个 MethodInfo 对象可表示有关某方法的信息。还有一个一般 MemberInfo 对象,它表示给定类中可以存在的所有成员。

使用该信息,您可设置以下数组来查看刚刚创建的类型,并弄清类型中有哪种类型的信息。下面示例中的“位”运算符(|符号,或 Visual Basic 中的 BitOr)请求满足指定约束的类型的所有信息。该示例展示如何获取所有字段和所有方法。

// declare and populate the arrays to hold the information...
FieldInfo [] fi = t.GetFields (BindingFlags.Static |
		BindingFlags.NonPublic | BindingFlags.Public);     // fields

MethodInfo [] mi = t.GetMethods (BindingFlags.Static |
		BindingFlags.NonPublic | BindingFlags.Public);     // methods
C# VB  

下一步是迭代通过每个数组,并在屏幕上列出数组中的元素(显然,您将实际处理这些元素或标识数组中的某个特定元素)。有多种方法可以进行该操作,但在该示例中使用 Foreach(Visual Basic 中为 For Each)语句。



// iterate through all the method members
foreach (MethodInfo m in mi) {
	Console.WriteLine(m);
}

// iterate through all the field members
foreach (FieldInfo f in fi) {
	Console.WriteLine(f);
}

// etc.... for each array type
C# VB  

前面的代码工作良好,但请注意两条 Foreach(Visual Basic 中为 For Each)语句多么类似。将所有这些都写出来非常费力而且杂乱(并且如果以后更改代码,可能需要大量维护)。可以通过返回到 MemberInfo 对象来规避这一点。MemberInfo 对象包括所有可能的信息集(方法、字段和接口等等)。这可以对我们有所帮助,因为我们可以将以前的多个 Foreach 语句写成一个语句,传入数组以进行分析。

// call the routine below, passing the relevant array we made in the previous step
PrintMembers( mi ); // the method information
PrintMembers( fi ); // the field information

void PrintMembers (MemberInfo [] ms ) {



	// MemberInfo is the generic info object. This can be any of the other info objects.
	foreach (MemberInfo m in ms) {
		Console.WriteLine(m);
	}
}
C# VB  

运行该示例时您将注意到,同时会发生其他一些事情。不必硬编码 System.String 对象,可以指定要获取有关哪个类的信息。它还使您可以控制是要显示静态信息还是实例信息。

原文地址:https://www.cnblogs.com/haoxiaobo/p/117032.html