在源生成器中查找所有派生类

问题描述 投票:0回答:1

我的源生成器需要找到从检查的类派生的其他类,以了解是否需要添加特殊代码。到目前为止,我只检查了该类以增强自身并跟踪其中的引用,例如类属性的类型,但没有检查使用源生成器的项目中也存在的任何其他类。我似乎找不到任何方法或接口或网络文档。这可能吗?它是如何运作的?

我正在寻找这样的东西:

public static IEnumerable<string> GetDerivedTypes(this ITypeSymbol typeSymbol)
{
    // TODO: Find all available classes,
    // then I can proceed with inheritance checks and further tests
    // Following is made-up code:
    var derivedTypeNames = typeSymbol.ContainingAssembly.AllTypes
        .Where(t => t.IsDerivedFrom(typeSymbol))
        .Select(t => t.Name);
    return derivedTypeNames;
}
c# .net roslyn sourcegenerators
1个回答
0
投票

也许你可以倒退?创建一个有先例的类型列表然后进行研究?

Type.BaseType 属性

using System;

public class Example
{
   public static void Main()
   {
      foreach (var t in typeof(Example).Assembly.GetTypes()) {
         Console.WriteLine("{0} derived from: ", t.FullName);
         var derived = t;
         do { 
            derived = derived.BaseType;
            if (derived != null) 
               Console.WriteLine("   {0}", derived.FullName);
         } while (derived != null);
         Console.WriteLine(); 
      } 
   }
}

public class A {} 

public class B : A
{}

public class C : B   
{}
// The example displays the following output:
//       Example derived from:
//          System.Object
//       
//       A derived from:
//          System.Object
//       
//       B derived from:
//          A
//          System.Object
//       
//       C derived from:
//          B
//          A
//          System.Object
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.