Recursion through class properties

Take this sample example:

    [AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
public class BugFixAttribute : System.Attribute
{
    public int BugId { get; private set; }
    public string Programmer { get; private set; }
    public DateTime Date { get; private set; }
    public string Comments { get; set; }
    public string RefersTo { get; set; }

    public BugFixAttribute(int bugId = 0, string programmer = "")
    {
        this.BugId = bugId;
        this.Programmer = programmer;
        Date = DateTime.Now;
    }
}

And I want to discard properties that can be used, for example:

object[] attr = info.GetCustomAttributes(typeof(BugFixAttribute), false);
foreach (object attribute in attr)
{
    BugFixAttribute bfa = (BugFixAttribute) attribute;
    Debug.WriteLine(string.Format("\nBugId: {0}", bfa.BugId));
    Debug.WriteLine(string.Format("Programmer: {0}", bfa.Programmer));
    //...
}

Because I need to do this in order to print them in a file. So, how can I recursively go through properties instead of doing Debug.WriteLine()through all of them, is there a way or do I need to write it.

+3
source share
5 answers

, , , , , . , XML, XML- .

:

/// <summary>This Method Does Something</summary>
/// <BugFix BugId="1234" Programmer="Bob" Date="2/1/2010">Fix Comments</BugFix>
public void MyMethod()
{
    // Do Something
}
+6

, :

Type t = bfa.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach(var prop in properties)
{
    Debug.WriteLine(string.Format("{0}: {1}", prop.Name,prop.GetValue(bfa,null)));
}

bfa. CanRead PropertyInfo, , (.. getter). , - , .

+4

Linq

var props = from b in info.GetCustomAttributes(typeof(BugFixAttribute), false)
            from p in b.GetType().GetProperties()
            select new { 
                   Name = p.Name,
                   Value = p.GetValue(p.GetValue(b, null))
                   };

foreach(var prop in props)
{
    Debug.WriteLine(string.Format("{0}: {1}", prop.Name, prop.Value));
}
+2

, , ? :

  • , , ( , java - .NET, , ...)
  • toString() Debug.WriteLine(bfa)

1, , way overkill. , , , .

2 - .

public class BugFixAttribute : System.Attribute
{
 ...

 public String toString(){
   return string.Format("\nBugId: {0}\nProgrammer: {1}", this.BugId, this.Programmer));
 }
}
0
foreach (var (BugFixAttribute)attribute in attr)
{
    foreach(PropertyInfo prop in attribute.GetType().GetProperties())
    {
        Debug.WriteLine(string.Format("{0}: {1}", prop.name,prop.GetValue(attribute,null));
    }
}
0

Source: https://habr.com/ru/post/1735325/


All Articles