我有一个类Letters
,它从接口IA
继承,而IA
从接口IB
继承。如何使用roslyn接口IA
和IB
? (我有ClassDeclarationSyntax
)
public interface IB
{
}
public interface IA : IB
{
}
public class Letters:IA
{
}
答案 0 :(得分:1)
尝试类似的东西
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);
}
答案 1 :(得分:0)
仅当您试图使用反射来访问类型信息时,其他答案才有效。
要使用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;