I cannot seem to retrieve a nested class using Roslyn's Compilation.GetTypeByMetaDataName()
method.
For example:
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 retrieve nested types using their fully qualified names?
I realize one work around would be to first check if the containing type contained any types using INamespaceorTypeSymbol.GetTypeMembers()
, but I would much rather not go down that path. I'd assume the GetTypeByMetaDataName()
method should work for any type, nested or otherwise.
Try using +
to separate inner classes:
var innerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass+MyInnerClass");
The documentation for the Type.GetType
method discusses the syntax used for naming nested types.
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.