NRefactory attributes with class

544 Views Asked by At

I'm tring to find all classes and the attributes above this class with NRefactory, but unfortunate I'm (yet) unable to achieve this.

What is the best approach to tackle this issue? I'm able to find the attributes, but how am I sure that it belongs to a certain class?

2

There are 2 best solutions below

0
Mittchel On

Following code did the trick:

        StreamReader reader = new StreamReader(@"..\..\demo.cs");
        var tex = reader.ReadToEnd();

        var syntaxTree = new CSharpParser().Parse(tex, tex);

        var testClass = syntaxTree.Descendants.OfType<TypeDeclaration>().Single(x => x.ClassType == ClassType.Class);
        var testClassAttributes = testClass.Attributes.SelectMany(x => x.Attributes).ToArray();
0
Dariusz Woźniak On

You can use following method:

IEnumerable<ICSharpCode.NRefactory.CSharp.Attribute> GetAttributes(TypeDeclaration typeDeclaration)
{
    return typeDeclaration.Members
        .SelectMany(member => member
            .Attributes
            .SelectMany(attr => attr.Attributes));
}