I'm trying to retrieve all the IMethodSymbols within a given type. For closed types (ie. types without generics) I can just use CSharpCompilation.GetTypeByMetaDataName() and pass in the fully qualified type name.
However, with an open type (eg. MyClass<T>
) the fully qualified name doesn't seem to work. I've tried supplying the fully qualified name without the type parameter (MyClass
), and also with a closed type (MyClass<int>
), but neither seems to work.
What's the best way to find this type using its fully qualified name?
Roslyn code models are immutable, like working with a .NET string; when you update the string, you get a new string object in return. When you call ReplaceNode, you get back a new root node.
The SyntaxNodeAnalysisContext, for example, has a CancellationToken that you can pass around. If a user starts typing in the editor, Roslyn will cancel running analyzers to save work and improve performance. As another example, this context has a Node property that returns the object creation syntax node.
Roslyn analyzers and code-aware library for ImmutableArrays. The .NET Compiler Platform ("Roslyn") helps you build code-aware libraries. A code-aware library provides functionality you can use and tooling (Roslyn analyzers) to help you use the library in the best way or to avoid errors.
The API Compilation.GetTypeByMetadataName is not intended as a replacement for using a compiler and the diagnostics the compiler produces. As you've found, there are other APIs that give you the behavior you need.
As mentioned in the comments, the compiler convention is to take a class name like MyClass<T>
and represent it as
MyClass`1
A working example:
var tree = CSharpSyntaxTree.ParseText(@"
public class MyClass<T> {
public static T Method()
{
}
}");
var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { mscorlib });
var type = compilation.GetTypeByMetadataName("MyClass`1");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With