如何在程序集中查找实例化类 X 对象的所有方法?
这里有一个有趣的问题:在我当前的项目中,我们使用的是一个配置非常繁重的自定义性能监控套件(它使用 Perfmon,因此我们必须手动注册每个性能计数器。我们监控的每种方法都有一个性能计数器,并且有很多这样的)。
我想知道是否有任何工具可以让我分析项目程序集,找到实例化类 XClass 实例的所有方法,然后将它们写入文件?这将使我能够大幅减少需要执行的手动配置量。
谢谢,Ed
编辑
抱歉,“将它们写入文件”的事情有点做作:实际上我需要用一些额外的数据重新格式化它们,并以特定于配置的 XML 格式写入它们。如果我可以对其进行编码,以便将其设置为构建任务(这样我就不必手动运行它),并且可以轻松进行任何未来的更改并记录下来,这将是最好的。
Interesting question here: In my current project we're using a custom performance monitoring suite that is very config-heavy (it uses Perfmon so we have to manually register each performance counter. There is one performance counter for each method that we monitor, and there are a lot of those).
I was wondering if there are any tools that would, say, allow me to analyse the project assembly, find all methods that instantiate an instance of class XClass, then write them out to a file? This would allow me to cut down the amount of manual config I need to do by a large margin.
Thanks, Ed
EDIT
Sorry, the 'write them to a file' thing was a little contrived: really I need to reformat them with some extra data and write them in a config-specific XML format. This would be best if I can code it up so it can be set as a build task (so I don't have to run it manually) and any future changes can be made easily and documented etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要编写代码来自动执行任务,可以使用 Mono.Cecil 轻松完成。例如,以下代码搜索程序集顶级类型的所有方法以实例化类 Foo.Bar.Baz:
If you need to write code to automate your task, it's easy to do it with Mono.Cecil. As an example, this code searches through all the methods of the top level types of an assembly for the instantiation of a class Foo.Bar.Baz:
看看NDepend。它是一个静态分析工具,具有非常强大的查询语言:CQL(代码查询语言)。
更新
NDepend 有一个控制台应用程序,可以推动自动化(例如,在构建系统中使用)并可以将报告输出到文件。
用于查找实例化已定义类型的方法的示例查询:
Take a look at NDepend. It's a static analysis tool with a very powerful query language: CQL (Code Query Language).
Update
NDepend has a console application that can be prodded for automation (e.g. for use in a build systems) and can output reports to file.
An example query to find methods which instantiate a defined type:
您可能想更改您的设计,以便他们使用工厂,这样工厂就负责额外的簿记。
也就是说,您可以在 System.Reflection 命名空间中(从内存中)查找使用 Assembly 类的位置。
You probably want to change your design so that they use a factory instead, such that the factory is responsible for the extra bookkeeping.
That said, you can look in the System.Reflection namespace, (from memory), where the Assembly class is used.
在 Reflector 中打开程序集(免费版本即可);找到类型 (F3),然后调出分析器 (Ctrl+R) 并展开“实例化依据”节点。
然后右键单击“Instantiated By”节点本身并单击复制;例如:
Open the assembly in Reflector (the free version is fine); find the type (F3), then bring up the anaylyzer (Ctrl+R) and expand the "Instantiated By" node.
Then right-click on the "Instantiated By" node itself and click copy; for example: