Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recurse through properties of a class

Take this sample class as an 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 recuse through the properties to use like:

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 what I need to do is to print these to a file. So how can I recurse through the properties instead of doing the Debug.WriteLine() through all of them, is there a way or do I have to write it out.

like image 356
Mohit Deshpande Avatar asked Jan 27 '26 21:01

Mohit Deshpande


1 Answers

I would suggest that this is probably not a great use for Attributes, as it muddies up the meta attached to the code. If you want to standardize a way to get at this sort of information regarding bug fixes, I would suggest coming up with an XML Comment Tag, and then turning on XML Comments for your project, and using that instead.

Example Syntax:

/// <summary>This Method Does Something</summary>
/// <BugFix BugId="1234" Programmer="Bob" Date="2/1/2010">Fix Comments</BugFix>
public void MyMethod()
{
    // Do Something
}
like image 177
Nick Avatar answered Jan 29 '26 11:01

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!