1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;
namespace Misc
{
/// <summary>
/// 继承IComparer<T>接口,实现同一自定义类型 对象比较
/// </summary>
/// <typeparam name="T">T为泛用类型</typeparam>
public class Reverser<T> : IComparer<T>
{
private Type type = null;
private ReverserInfo info;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name">进行比较对象的属性名称</param>
/// <param name="direction">比较方向(升序/降序)</param>
public Reverser(string name, ReverserInfo.Direction direction)
{
this.type = typeof(T);
this.info.name = name;
if (direction != ReverserInfo.Direction.ASC)
this.info.direction = direction;
}
//必须!实现IComparer<T>的比较方法。
int IComparer<T>.Compare(T t1, T t2)
{
object x = this.type.InvokeMember(this.info.name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, t1, null);
object y = this.type.InvokeMember(this.info.name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, t2, null);
if (this.info.direction != ReverserInfo.Direction.ASC)
Swap(ref x, ref y);
return (new CaseInsensitiveComparer()).Compare(x, y);
}
//交换操作数
private void Swap(ref object x, ref object y)
{
object temp = null;
temp = x;
x = y;
y = temp;
}
}
/// <summary>
/// 对象比较时使用的信息类
/// </summary>
public struct ReverserInfo
{
/**/
/// <summary>
/// 比较的方向,如下:
/// ASC:升序
/// DESC:降序
/// </summary>
public enum Direction
{
ASC = 0,
DESC,
};
public enum Target
{
CUSTOMER = 0,
FORM,
FIELD,
SERVER,
};
public string name;
public Direction direction;
public Target target;
}
}