如何通过 Roslyn 找到 base class 的命名空间

How to find a namespace of base class via Roslyn

我正在编写源代码生成器,它制作简单 DTO 类 的副本(有一些小改动)。我已经复制了所有包含的属性并且一切正常。但是我的一些 类 是从另一个像这样继承的:

public class MyClass : MyBaseClass
{
    public string MyProperty { get; set; }
}

我不能只复制继承声明,因为我复制的 类 位于不同的命名空间中。所以我需要将 using 添加到 MyBaseClass 的命名空间,所以我需要找到比命名空间。我已经使用语义模型为我的 属性 类型完成了此操作,如下所示:

Compilation
   .GetSemanticModel(propertyNode.Type.SyntaxTree)
   .GetSymbolInfo(propertyNode.Type)
   .Symbol
   .ContainingNamespace

但是我在从基类型获取命名空间时遇到了意想不到的问题。我现在尝试过的:

// list of all base types
var typeList = classNode.BaseList;                  
var semanticModel = Compilation.GetSemanticModel(typeList.SyntaxTree);

var symbol = semanticModel.GetSymbolInfo(typeList); // symbol.Symbol is null
var type = semanticModel.GetTypeInfo(typeList);     // type.Type is null 
// list of all base types
var firstType = classNode.BaseList.Types[0]; 
var semanticModel = Compilation.GetSemanticModel(firstType.SyntaxTree);

var symbol = semanticModel.GetSymbolInfo(firstType); // symbol.Symbol is null
var type = semanticModel.GetTypeInfo(firstType);     // type.Type is null 
// list of all base types
var typeList = classNode.BaseList;
var semanticModel = Compilation.GetSemanticModel(typeList.SyntaxTree);

var symbol = semanticModel.GetSymbolInfo(typeList.Types[0]); // symbol.Symbol is null
var type = semanticModel.GetTypeInfo(typeList.Types[0]);     // type.Type is null 

我不知道出了什么问题。我试图用不同的参数调用不同的方法,但没有得到正确的结果。可能有另一种方法可以做到这一点?

尝试:

semanticModel.GetSymbolInfo(typeList.Types[0].Type)

(注意里面多出来的“.Type”)