简体   繁体   中英

.Net Reflection GetProperties()

I've encountered a weird issue while using Reflection.

So I have a domain class with different properties. Depending on the needs, some properties are filled and some are not.

In the GUI, I iterate through the properties via GetProperties() and display them according to their value. (Empty not shown, not empty is shown).

But! The first time I iterate the properties, the order of the properties is different then the next times.

So the first time I get "ObjectMetaClassName"=>"ShortName"=>"Name"=>"Url".

Subsequent times I get "ObjectMetaClassName"=>"ShortName"=>"Url"=>"Name".

Does anyone have an explanation for this, why this occurs?

From http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx :

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.

If order is important, perhaps you should try sorting the results?

Update Custom sorting

This will add some complexity, but you could add custom sort order to the results using attributes. First, create the custom attribute SortOrderAttribute :

[AttributeUsage(AttributeTargets.Property)]
public sealed class SortOrderAttribute : Attribute
{
    private int _sortOrder;

    public SortOrderAttribute(int sortOrder)
    {
        _sortOrder = sortOrder;
    }
}

Next apply that attribute to the properties on your class:

public class Foo
{
    [SortOrder(1)]
    public int Bar { get; set; }

    [SortOrder(2)]
    public string Name { get; set; }
}

Then an IComparer:

public class PropertyInfoComparer : IComparer<PropertyInfo>
{
    public int Compare(PropertyInfo a, PropertyInfo b)
    {
        return a.GetCustomAttributes(typeof(SortOrderAttribute), false)[0] - b.GetCustomAttributes(typeof(SortOrderAttribute), false)[0];
    }
}

Finally, to get the sorted list:

public PropertyInfo[] SortedList()
{
    PropertyInfo[] properties = typeof(Foo).GetProperties();
    Array.Sort(properties, new PropertyInfoComparer());
    return properties;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM