简体   繁体   English

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

[英]How to get from class all the interfaces it inherits (using roslyn)?

I have a class Letters that inherits from interface IA , and IA inherits from interface IB .我有一个继承自接口IA的 class Letters ,而IA继承自接口IB How can I get with roslyn the interfaces IA and IB ?我怎样才能使用 roslyn 接口IAIB (I have ClassDeclarationSyntax ) (我有ClassDeclarationSyntax

public interface IB
{
}
public interface IA : IB
{
}
public class Letters:IA
{
}

Try something like,尝试类似的东西,

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

Edit #1编辑#1

for dynamic class name,对于动态 class 名称,

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

The other answers are valid only if you're trying to use reflection to access type information.仅当您尝试使用反射来访问类型信息时,其他答案才有效。

To use Roslyn you'll have to use the SemanticModel to get an INamedTypeSymbol for your Letters class and then use .AllInterfaces要使用 Roslyn,您必须使用SemanticModel为您的Letters class 获取INamedTypeSymbol ,然后使用.AllInterfaces

I don't have Roslyn installed but it should be something like:我没有安装 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM