How to get a list of all fields with the specified attribute?

I am trying to find fields with the specified attribute. I tried changing the FirstQuickFix example because, as I thought, this could be a good starting point. But if I run the code, nothing happens. Any ideas what is my main problem?

My understanding, after reading the Project Overview and walkthrough docs, is that I can request attributes for the token I found in the syntax tree. The syntax tree is an accurate tree view of the source code. The combination of a field declaration and its attributes is available through semantics. Or is my understanding completely wrong?

[ExportCodeIssueProvider("FirstQuickFix_", LanguageNames.CSharp)]
class CodeIssueProvider : ICodeIssueProvider
{
    public IEnumerable<CodeIssue> GetIssues
      (IDocument document, CommonSyntaxNode node, CancellationToken cancellationToken)
    {
        var tokens = from nodeOrToken in node.ChildNodesAndTokens()
                     where nodeOrToken.HasAnnotations(Type.GetType("myAttribute"))
                     select nodeOrToken.AsToken();

        foreach (var token in tokens)
        {
            var issueDescription = string.Format("found!!!");
            yield return new CodeIssue(CodeIssueKind.Info, token.Span, issueDescription);
        }
    }
}

Edit:

what I want to achieve is to find that. all fields with the myAttribute attribute:

namespace ConsoleApplication
{
    class Program
    {
        [myAttribute]
        string myField = "test";

        public void testing()
        {
            Console.WriteLine(myField);
        }
    }
}
+5
source share
3 answers

, LINQ AttributeSyntax , Parent (), node, :

var fields = root.DescendantNodes()
                 .OfType<AttributeSyntax>()
                 .Where(a => a.Name.ToString() == "myAttribute")
                 .Select(a => a.Parent.Parent)
                 .Cast<FieldDeclarationSyntax>();

, , , ( ) using .

, , , .

+5

, , LINQ Type.GetField:

using System.Collections.Generic;
using System.Linq;

class TestAttribute : System.Attribute { }

class State
{
    [Test] string name;
    [Test] string address;
    [Test] public string name2;
    [Test] public string address2;
    float height;
    public State(string name_, string address_, float height_)
    {
        name = name_;
        address = address_;
        height = height_;
        name2 = name_ + "2";
        address2 = address_ + "2";
    }
}

public class Program
{
    static void ShowFields<T>(IEnumerable<T> fieldList)
    {
        foreach (var field in fieldList)
        {
            System.Console.WriteLine(field.ToString());
        }
    }

    public static void Main(string[] args)
    {            
        State s = new State("Bob", "221 B Baker Street", 5.4f);
        System.Type stateType = typeof(State);
        System.Reflection.FieldInfo[] publicFieldList = stateType.GetFields();
        System.Console.WriteLine("----all public fields----");
        ShowFields(publicFieldList);

        System.Console.WriteLine("----all non public or instance fields----");
        System.Reflection.FieldInfo[] nonPublicFieldList;
        nonPublicFieldList = stateType.GetFields(System.Reflection.BindingFlags.NonPublic| System.Reflection.BindingFlags.Instance);
        ShowFields(nonPublicFieldList);

        var customAttributeFieldList = from t in stateType.GetFields()
        where t.GetCustomAttributes(false).Any(a => a is TestAttribute)
        select t;
        System.Console.WriteLine("----only public fields marked with a particular custom attribute----");
        ShowFields(customAttributeFieldList);
    }
}
0

Here is a working code example to iterate over properties with custom attributes in a class. You can use this hint for "How to get a list of all fields with the specified attribute?"

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();

        var type = myClass.GetType();

        foreach (var property in type.GetProperties())
        {
            //Get ALL custom attributes of the property
            var propattr = property.GetCustomAttributes(false);

            //Get MyAttribute Attribute of the Property
            object attr =
                (from row in propattr
                 where row.GetType() == typeof(MyAttribute)
                 select row).FirstOrDefault();
            if (attr == null || !(attr is MyAttribute))
                continue;

            var myAttribute = attr as MyAttribute;

            //output: NameAttrValue and AgeAttrValue 
            Console.WriteLine(myAttribute.Val);

            //Output: Name and Age
            Console.WriteLine(property.Name);
        }
    }
}

public class MyClass
{
    [My("NameAttrValue")]
    public string Name { get; set; }

    [My("AgeAttrValue")]
    public int Age { get; set; }


    public MyClass()
    {
        this.Name = "Jac";
        this.Age = 27;
    }
}

public class MyAttribute : Attribute
{
    public MyAttribute(string val)
    {
        this.Val = val;
    }

    public string Val { get; set; }
}
-3
source

All Articles