前端時間剛剛弄完一個項目,終於有時間來總結與回顧了。前端
項目需求:給用戶發送郵件,郵件分爲系統郵件和我的郵件,須要按時間、未讀降序排列。測試
一開始覺得,這是一個很簡單的需求,給郵件建了一個對象:this
class Mail{spa
private string _title =string.Empty;orm
public string Title{對象
get {return _title;}排序
}遊戲
private string _message = string.Empty;get
public string Message {string
get {return _message;}
}
private bool _isRead = false ;
public bool IsRead {
get {return _isRead}
}
privaite DateTime _insertTime = DateTime.Now;
public DateTime InsertTime{
get {return _insertTime ;}
}
}
而後再 List<Mail> listMails = new List<Mail> 進行冒泡排序(裏面已經按時間降序了,如今只需按未讀排序)
for(int i=0,count1=listMails.Count;i<count1;i++){
for(int j= i+1;j<count1;j++){
if(listMails[i].IsRead && !listMails[j].IsRead){
Mail temp = listMails[i];
listMails[i] = listMails[j];
listMails[j]=temp;
}
}
}
結果可想而知了,並未按未讀降序排列。
改進方法1:對Mail進行深度複製:
[Serializable]
class Mail:ICloneable{
private string _title =string.Empty;
public string Title{
get {return _title;}
}
private string _message = string.Empty;
public string Message {
get {return _message;}
}
private bool _isRead = false ;
public bool IsRead {
get {return _isRead}
}
privaite DateTime _insertTime = DateTime.Now;
public DateTime InsertTime{
get {return _insertTime ;}
}
public object Clone()
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, this);
objectStream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(objectStream) as Employee;
}
}
}
而後再 List<Mail> listMails = new List<Mail> 進行冒泡排序(裏面已經按時間降序了,如今只需按未讀排序)
for(int i=0,count1=listMails.Count;i<count1;i++){
for(int j= i+1;j<count1;j++){
if(listMails[i].IsRead && !listMails[j].IsRead){
Mail temp = (Mail)listMails[i].Clone();
listMails[i] = (Mail)listMails[j].Clone();
listMails[j]=temp;
}
}
}
結果仍是不行,鬱悶了。
最後採用值類型(struct)進行處理:
struct Mail{
private string _title;
public string Title{
get {return _title;}
}
private string _message;
public string Message {
get {return _message;}
}
private bool _isRead;
public bool IsRead {
get {return _isRead}
}
privaite DateTime _insertTime;
public DateTime InsertTime{
get {return _insertTime ;}
}
}
而後再 List<Mail> listMails = new List<Mail> 進行冒泡排序(裏面已經按時間降序了,如今只需按未讀排序)
for(int i=0,count1=listMails.Count;i<count1;i++){
for(int j= i+1;j<count1;j++){
if(listMails[i].IsRead && !listMails[j].IsRead){
Mail temp = listMails[i];
listMails[i] = listMails[j];
listMails[j]=temp;
}
}
}
測試,一切OK,建議全部的同窗,深刻理解值類型和引用類型,避免形成沒必要要的麻煩。