当前位置:编程学习 > C#/ASP.NET >>

代码重复,需要泛型复用

代码一:
   [Serializable]
    public class FavorableParamBindingList : BindingList<FavorableParam>, ICloneable
    {
        public object Clone()
        {
            MemoryStream ms = new MemoryStream();
            object obj;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, this);
                ms.Seek(0, SeekOrigin.Begin);
                obj = bf.Deserialize(ms);
            }
            finally
            {
                ms.Close();
            }

            return obj;
        }
    }

代码二:
  [Serializable] 
    public class FormulaParamCfgList : List<FormulaParamCfg>, ICloneable
    {
        public object Clone()
        {
            MemoryStream ms = new MemoryStream();
            object obj;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, this);
                ms.Seek(0, SeekOrigin.Begin);
                obj = bf.Deserialize(ms);
            }
            finally
            {
                ms.Close();
            }

            return obj;
        } 


    }

由于上面代码重复,需要把上面两段代码进行优化,进行泛型复用,请问如何改写成一个类
泛型 --------------------编程问答-------------------- 把序列化那一段拿出来写成一个函数,它接受泛型foo<T> --------------------编程问答--------------------   [Serializable]
    public class FavorableParamBindingList<T> : List<T>, ICloneable
    {
        public object Clone()
        {
            MemoryStream ms = new MemoryStream();
            object obj;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, this);
                ms.Seek(0, SeekOrigin.Begin);
                obj = bf.Deserialize(ms);
            }
            finally
            {
                ms.Close();
            }

            return obj;
        }
    }


调用时


类似这样的  
XQLS.Common.enmuList<XQLS.Common.CommonHelper> dd = new XQLS.Common.enmuList<XQLS.Common.CommonHelper>(); --------------------编程问答-------------------- 额,这代码太过常用了,所以无需独立封装

直接扩展方法改成对全体object公用的方法就ok --------------------编程问答-------------------- 你试试这种方法
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,