简体   繁体   中英

How I can get all reference with Reflection + C#

Using System.Reflection, I can get all methods from a specific class

I need know what are the references to these methods. For example: in Visual Studio, if you want the references of specific object

  • right click on the object and select "Find All References"
  • Visual Studio show the references of this selected object

I want make the same, but from code with reflection or another way.

Can I do this?

This cannot be done with reflection. Reflection is a tool for inspecting metadata and assemblies. In order to find all references to a given method / type, you'd need to inspect the underlying IL of an assembly. Reflection only has very limited IL capabilities (simply returns it as a byte array). You'll need to custom inspect that byte stream in order to gather any context about what it's referencing.

That's not something that's directly accessible via runtime reflection on a specific class. You will have to introspect the entire source code tree or resulting IL to determine if any references to a particular method with the same name are the right overload and signature for the method you're trying to find references to.

Furthermore, without additional work, you're never going to find references to a specific method that are themselves invoked via reflection. (This is one reason why obfuscating that kind of code is challenging and error-prone.)

If you're just looking to find the references for informational purposes, Reflector has that feature.

http://www.red-gate.com/products/reflector/

Microsoft released the Common Compiler Infrastructure projects under an open source license. These projects aim to support many compiler-related features, including assembly analysis like you're referring to. The documentation is limited, so you'll need to have a thorough understanding of ECMA-335 (Common Language Infrastructure) to effectively use it for your purposes.

There are no magic code samples here. This is a large and quite complicated task where you'll be on your own most of the way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM