C#中完美克隆引用類型的對象

我們都知道,在C#中,對於複雜對象,每聲明一個牸類型的變量a,並用個該類型的對象A給這個變量賦值的時候,其實是讓這個變量a指向了對象A,在內存中並沒有多生成一個對象A的實例.所以不管我們聲明多少個等於A的變量,其實際上永遠都只有一個A存在於內存中.這就是我們常說的引用類型的特性.

引用類型的這一特性的好處是不言無喻的,然而,它也給我們帶了一小點不便,那就是有時候,偶爾我們需要在內存中有兩個所有屬性值都一模一樣的對象A和B,這樣便於對B做操作而不影響到A.有人說那New兩次不就有兩個一模一樣的對象了嗎,其實,他沒有考慮到在實際的操作過程中,對象A可能因爲用戶的操作,一些屬性被改變了.New出來的對象只能確保初始狀態類型和屬性的一致性,對於運行時改變的屬性它就無能爲力了.也就是說,此時,我們得克隆一個A對象,把當前A對象的所有屬性值取到新對象中去,這樣就能保證當前兩個對象的一致性.看代碼吧:

/// 
/// 克隆一個對象
/// /// /// private object CloneObject(object o) { Type t =o.GetType(); PropertyInfo[] properties =t.GetProperties(); Object p =t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null); foreach(PropertyInfo pi in properties) { if(pi.CanWrite) { object value=pi.GetValue(o, null); pi.SetValue(p, value, null); } } return p; }
調用代碼生成新的一模一樣的對象就很方便了,示例:
TextBox t =(TextBox)CloneObject(textBox1);
當然,在實際使用的過程中,我發現上面的方法也是有缺陷的,比如在克隆DataGridView對象的時候,SetValue的時候會報錯,其中的原因還有待分析.不過我們還有更專業的克隆DataGridView的方法:
/// 
/// 專門克隆DataGridView的方法
/// 
/// 
/// public static DataGridView CloneDataGridView(DataGridView dgv)
{
    try
    {
        DataGridView ResultDGV = new DataGridView();
        ResultDGV.ColumnHeadersDefaultCellStyle = dgv.ColumnHeadersDefaultCellStyle.Clone();
        DataGridViewCellStyle dtgvdcs = dgv.RowsDefaultCellStyle.Clone();
        dtgvdcs.BackColor = dgv.DefaultCellStyle.BackColor;
        dtgvdcs.ForeColor = dgv.DefaultCellStyle.ForeColor;
        dtgvdcs.Font = dgv.DefaultCellStyle.Font;
        ResultDGV.RowsDefaultCellStyle = dtgvdcs;
        ResultDGV.AlternatingRowsDefaultCellStyle = dgv.AlternatingRowsDefaultCellStyle.Clone();
        for (int i = 0; i < dgv.Columns.Count; i++)
        {
            DataGridViewColumn DTGVC = dgv.Columns[i].Clone() as DataGridViewColumn;
            DTGVC.DisplayIndex = dgv.Columns[i].DisplayIndex;
            if (DTGVC.CellType == null)
            {
                DTGVC.CellTemplate = new DataGridViewTextBoxCell();
                ResultDGV.Columns.Add(DTGVC);
            }
            else
            {
                ResultDGV.Columns.Add(DTGVC);
            }
        }
        foreach (DataGridViewRow var in dgv.Rows)
        {
            DataGridViewRow Dtgvr = var.Clone() as DataGridViewRow;
            Dtgvr.DefaultCellStyle = var.DefaultCellStyle.Clone();
            for (int i = 0; i < var.Cells.Count; i++)
            {
                Dtgvr.Cells[i].Value = var.Cells[i].Value;
            }
            if (var.Index % 2 == 0)
                Dtgvr.DefaultCellStyle.BackColor = ResultDGV.RowsDefaultCellStyle.BackColor;
            ResultDGV.Rows.Add(Dtgvr);
        }
        return ResultDGV;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    return null;
}

現在就沒有遺憾了.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章