編程時遇到排序在平常不過
void Sort<T>(T[] array
{
if (left < right)
{
T middle = array[(left + right) /
int i = left
int j = right +
while (true)
{
while (array[++i]
while (array[
if (i >= j)
break;
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Sort(array
Sort(array
}
}
問題
對於前兩種情況固然可以實現排序
按照面向對象的思想
編寫通用的List<T>排序方法首先定義一個接口
public interface IComparer_sly<T>{
int Compare(T x
}
然後為了測試
using System;
using System
namespace Test
{public class ListTest<T>
{
public List<T> list = new List<T>();
public void Sort(IComparer_sly<T> comparer)
{
T[] array = list
int left =
int right = array
QuickSort(array
list = new List<T>(array);
}
private void QuickSort<S>(S[] array
{
if (left < right)
{
S middle = array[(left + right) /
int i = left
int j = right +
while (true)
{
while (comparer
while (comparer
if (i >= j)
break;
S temp = array[i];
array[i] = array[j];
array[j] = temp;
}
QuickSort(array
QuickSort(array
}
}
}
}比如現在我們有個Student 的實體
public class Student
{
public Student(int id
{
this
this
}
public int ID { get; set; }
public string Name { get; set; }
}
如果想對這個實體組成的List<T>進行排序
class StudentComparer : IComparer_sly<Student>
{
private string expression;
private bool isAscending;
public StudentComparer(string expression
{
this
this
}
public int Compare(Student x
{
object v
if (v
{
string s
string s
if (s
return
else if (s
return
else if (s
return
}
// 這裡就偷懶調用系統方法
if (!isAscending)
return Comparer
return Comparer
}
private object GetValue(Student stu)
{
object v = null;
switch (expression)
{
case
v = stu
break;
case
v = stu
break;
default:
v = null;
break;
}
return v;
}
}測試一下好不好使
static void Main(string[] args)
{
ListTest<Student> test = new ListTest<Student>();
for (int i =
{
Student stu = new Student(i
test
}
Console
for (int i =
{
Console
}
Console
test
for (int i =
{
Console
}
}看看效果
策略模式看清楚了上面這個例子我們就可以進入正題
這個模式涉及到三個角色
相信大家可以分方便的把我們上面例子中的類對應上策略模式的角色
From:http://tw.wingwit.com/Article/program/net/201311/12248.html