How can I get a nested type with its full name?

I cannot find a nested class using the Roslyn method Compilation.GetTypeByMetaDataName().

For instance:

var tree = CSharpSyntaxTree.ParseText(@"
using System;
namespace MyNamespace
{
    public class MyClass 
    {
        public class MyInnerClass
        {
        }
    }
}
");

var Mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });

//Correctly retrieves outer type.
var outerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass");
//Cannot correctly retrieve inner type (returns null)
var innerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass.MyInnerClass");

Is it possible to extract nested types using their fully qualified names?

I understand that one work around would be to first check if the containing type contains any types using INamespaceorTypeSymbol.GetTypeMembers(), but I would probably not go this way. I would suggest that a method GetTypeByMetaDataName()should work for any type, nested or otherwise.

+4
source share
1 answer

Try using +to separate inner classes:

var innerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass+MyInnerClass");

Type.GetType , .

+6

Source: https://habr.com/ru/post/1545140/


All Articles