简体   繁体   中英

Is it possible to instantiate and call a method of the class my Analyzer is analyzing right now?

My analyzer will match methods with certain signatures. I would like from inside my analyzer to create an instance of the class I'm analyzing and call the method that caused the analyzer to kick in.

Assuming the source code is in a compilable state, is it possible?

Getting the class name and method name is pretty easy, but Type.GetType(...) will always return null.

The purpose of this is that I would like for my analyzer to kick in when I'm on a test method and run it, failing if the test fails.

If the code is not ready for compilation, it would be fine to just return.

It seems possible, but you'd need to check the efficiency of these solutions. Also, you can't guarantee that the code is compilable.

You can grab the Compilation object (from let's say context.SemanticModel.Compilation ), call Emit on it, and write it to disc. Then use Assembly.Load to load it, and then it's simple reflection to instantiate the class, whose name you already know, and call the method on it with appropriate arguments.

Another approach would be to use the Compilation in a scripting session as a reference assembly, and use the Roslyn Scripting API to invoke the method. There is a ToMetadataReference method on the Compilation , so you could get a MetadataReference , which could be then passed to ScriptOptions.Default.AddReferences . And then you'd need to pass the resulting options instance to CSharpScript.EvaluateAsync() .

There's another fundamental reason you can't run code from the user's compilation, even if it did actually compile -- it might be the wrong environment. Consider a scenario where you're targeting Windows Phone, or Xamarin Android/iOS, .NET Core on Linux, or whatever. In any of these cases the compiler has reference assemblies that you can compile against but obviously you can't actually run that code because it's targeting a different platform. People often ask why you can't convert an ITypeSymbol to a reflection System.Type and back, and this is one of the reasons why -- the compiler can compile code on platform A for platform B, when it can't actually run (or fully load) B's assemblies in the first place.

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