using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LB_SmartVisionCommon
{
///
/// 属性排序
///
public class PropertySorter : ExpandableObjectConverter
{
///
/// 获取支持的属性
///
/// 提供有关组件(例如其容器和属性描述符)的上下文信息。
/// 执行是否成功
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
///
/// 获取属性描述符集合
///
/// 提供有关组件(例如其容器和属性描述符)的上下文信息。
/// 值
/// 自定义特性
/// 返回属性描述符集合
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(value, attributes);
ArrayList orderedProperties = new ArrayList();
foreach (PropertyDescriptor pd in pdc)
{
Attribute attribute = pd.Attributes[typeof(PropertyOrderAttribute)];
if (attribute != null)
{
PropertyOrderAttribute poa = (PropertyOrderAttribute)attribute;
orderedProperties.Add(new PropertyOrderPair(pd.Name, poa.Order));
}
else
{
orderedProperties.Add(new PropertyOrderPair(pd.Name, 0));
}
}
orderedProperties.Sort();
ArrayList propertyNames = new ArrayList();
foreach (PropertyOrderPair pop in orderedProperties)
{
propertyNames.Add(pop.Name);
}
return pdc.Sort((string[])propertyNames.ToArray(typeof(string)));
}
}
///
/// 属性排序属性类
///
[AttributeUsage(AttributeTargets.Property)]
public class PropertyOrderAttribute : Attribute
{
///
/// 序号
///
private int _order;
///
/// 属性排序属性
///
/// 序号
public PropertyOrderAttribute(int order)
{
_order = order;
}
///
/// 属性序号
///
public int Order
{
get
{
return _order;
}
}
}
///
/// 属性顺序对类
///
public class PropertyOrderPair : IComparable
{
private int _order;
private string _name;
///
/// 名称
///
public string Name
{
get
{
return _name;
}
}
///
/// 属性顺序对
///
/// 名称
/// 序号
public PropertyOrderPair(string name, int order)
{
_order = order;
_name = name;
}
///
/// 比对排序
///
/// 自定义属性
///
public int CompareTo(object obj)
{
int otherOrder = ((PropertyOrderPair)obj)._order;
if (otherOrder == _order)
{
string otherName = ((PropertyOrderPair)obj)._name;
return string.Compare(_name, otherName);
}
else if (otherOrder > _order)
{
return -1;
}
return 1;
}
}
}