tags:

views:

79

answers:

3

I have one class that inherits another. I want to use reflection to cycle through the properties and write the values to a file. No problem. Except that I want to control the order in which the properties write out. Is there a clean way to do this? Right now, problem 1 is that the properties in the the subclass write out and THEN the proepries in the parent class write out. But also, I may want to skip some properties or just reorder them.

Here is my code now...

foreach (PropertyInfo bp in t.GetProperties())
{
    Type pt = bp.PropertyType;

    if ((pt.IsArray) && pt.FullName == "System.Char[]")
    {
        char[] caPropertyValue;
        caPropertyValue = (char[])(bp.GetValue(oBatch, null));
        string strPropertyValue = new string(caPropertyValue);
        myBatch.Add(strPropertyValue);
    }
}
+3  A: 

The easiest way would be to order them by their name - alphabetically. You could also group them by class they belong to and then order each group by name. LINQ makes such operations relatively easy:

foreach( PropertyInfo bp in t.GetProperties()
                             .OrderBy( p => p.Name ) 
{...}

or

foreach( PropertyInfo bp in t.GetProperties()
                             .OrderBy( p => p.Name )
                             .GroupBy( p => p.DeclaringType.FullName )
                             .OrderBy( g => g.Key )
                             .SelectMany( g => g ) )
{...}
LBushkin
Along with that you could also then decorate your properties with custom attributes like SortOrderAttribute() or DontExportAttribute() and then call GetCustomAttributes() on the property and perform whatever logic you want.
Chris Haas
A: 

check out the GetProperties syntax. There's a parameter to tell it whether or not you want attributes for the current class only or, as you're asking, for the entire inheritance chain. You will have to walk your class structure to find the attributes at each level.

No Refunds No Returns
A: 

You could create your own Attribute i.e. '''OrderAttribute''' and place it over property such as

public class Man
{
   [Order(0)]
   string Name {get; set;}
   [Order(1)]
   int virtual Age {get; set;}
}
public class SuperMan:Man
{
   [Order(-1)]
   override int Age {get; set;}
}

in the sorting routine you can check order attribute value via pi.GetCustomAttribute() and sort pi's over it.

Sergey Mirvoda