如何从类中获取它继承的所有接口(使用roslyn)?

我有一个类Letters,它从接口IA继承,而IA从接口IB继承。如何使用roslyn接口IAIB? (我有ClassDeclarationSyntax

public interface IB
{
}
public interface IA : IB
{
}
public class Letters:IA
{
}
jksaghefi 回答:如何从类中获取它继承的所有接口(使用roslyn)?

尝试类似的东西

 var interFacesOfLetters = typeof(Letters).GetInterfaces();
            foreach (var x in interFacesOfLetters)
            {
                Console.WriteLine(x.Name);
            }

编辑#1

对于动态类名,

  var name = "NameSpaceName.Letters";
  var interFacesOfLetters = Type.GetType(name).GetInterfaces();
  foreach (var x in interFacesOfLetters)
  {
    Console.WriteLine(x.Name);
  }
,

仅当您试图使用反射来访问类型信息时,其他答案才有效。

要使用Roslyn,您必须使用SemanticModel来为INamedTypeSymbol类获得Letters,然后使用.AllInterfaces

我没有安装Roslyn,但是应该像这样:

var tree = CSharpSyntaxTree.ParseText(@"
public interface IB
{
}
public interface IA : IB
{
}
public class Letters:IA
{
}
");

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

var myClass = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Last();
var myClassSymbol = model.GetDeclaredSymbol(myClass);

var interfaces = myClassSymbol.AllInterfaces;
本文链接:https://www.f2er.com/3167836.html

大家都在问