-1

My task is to find properties with certain attributes out of .cs files. So I get .cs files and I have to search them for certain attributes and save them in XML.

So every propertie with the attribute [ID] I should store the value together with the ID. In the context how I should realize this the word 'Just-in-time compiler' and 'reflection' are used. But I have no idea how to start, because I never worked with Just-in-Time compiler/reflections before.

First I tried it with regular expressions but there I wasn't able to get the properties. How can I get the property value when I load the .cs file as a string? (or what should I do instead?) .cs file in that I search:

[ID(12345678)]
public string quack {get; set}

My script that I tried:

string document = File.ReadAllText(@"FilePath.cs");
    var searchPatternID = @"(?<![\p{Zs}\t]*//.*)(?<!/\*(?:(?!\*/)[\s\S\r])*?)\[[\n\r\s]*ID(.*?\n*?)*?\]";

    var matches = Regex.Matches(document, searchPatternID );

     foreach (var m in matches)
     {
         Console.WriteLine(m);
     }

Here I only search for the ID. How do I can get the value of "quack"?

What I expect:

[ID(12345678)]
public string quack {get; set}

public string wuff {get; set}

Here I would expect the value of quack together with the ID.

  • Are you sure you want to search the *.cs files? These are not available after distribution. You probably want to use reflection to search for the properties/attributes, see here how to check a property for an attribute: https://stackoverflow.com/a/2051116/4035472. – thehennyy Jun 24 '19 at 08:24

2 Answers2

1

You can Use this code

var properties = typeof(MyClass).GetProperties();
        var specificProperty = properties.Where(t => t.CustomAttributes.Any(y => y.AttributeType.FullName == "MyTestAttribute")).ToList()
            .Select(z=>z.CustomAttributes).ToList();
        var values = specificProperty.Select(s => s.First().ConstructorArguments.First().Value).ToList();
Mofid.Moghimi
  • 907
  • 1
  • 6
  • 13
0

If you want to get ID attribute you have to get CustomAtributes by typeof() or .GetType().

var attributes = typeof(YourClass).CustomAttributes;

Then you can look for your attribute and its value or whatever you want.

So you can get all of properties and then look for attribute:

    var properties = typeof(YourClass).Properties();
    foreach (var prop in properties)
    {
        prop.CustomAttributes.CheckAttribute();
    }