前端時間剛剛弄完一個項目,終於有時間來總結與回顧了。
項目需求:給用戶發送郵件,郵件分為系統郵件和個人郵件,需要按時間、未讀降序排列。
一開始以為,這是一個很簡單的需求,給郵件建了一個對象:
class Mail{
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 ;}
}
}
然後再 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,建議所有的同學,深入理解值類型和引用類型,避免造成不必要的麻煩。
轉載,請注明來源,手游基地 www.shouyou888.com,QQD123游戲網 www.qqd123.com