Re: MemberwiseClone() doesn't like arrays?
- From: Marc Gravell <marc.gravell@xxxxxxxxx>
- Date: Mon, 10 Mar 2008 04:02:37 -0700 (PDT)
OK; maybe I got side-tracked by the deep-copy issue. If you just want
shallow... fine...
You can't use MemberwiseClone because it will copy the base-class
properties (such as the array reference) - but perhaps something
involving *encapsulation* (rather than inheritance) provides the
route? Then you only have to worry about cranking one field (the
reference to the backing list); note I've used a base-class to *just*
provide the encapsulation, with the specific functionality (Text etc)
in a subclass:
public class NamedList : CloneList
{
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
}
public class CloneList : IList, ICloneable
{
ArrayList list = new ArrayList();
public object Clone()
{
NamedList clone = (NamedList) MemberwiseClone();
// now swap the backing list
clone.list = (ArrayList) list.Clone();
return clone;
}
public int Add(object value) {
return list.Add(value);
}
public void Clear() {
list.Clear();
}
public bool Contains(object value) {
return list.Contains(value);
}
public int IndexOf(object value) {
return list.IndexOf(value);
}
public void Insert(int index, object value) {
list.Insert(index, value);
}
public bool IsFixedSize {
get { return list.IsFixedSize; }
}
public bool IsReadOnly {
get { return list.IsReadOnly; }
}
public void Remove(object value) {
list.Remove(value);
}
public void RemoveAt(int index) {
list.RemoveAt(index);
}
public object this[int index] {
get {return list[index];}
set {list[index] = value;}
}
public void CopyTo(Array array, int index) {
list.CopyTo(array, index);
}
public int Count {
get { return list.Count; }
}
bool ICollection.IsSynchronized {
get { return list.IsSynchronized; }
}
object ICollection.SyncRoot {
get { return list.SyncRoot; }
}
public IEnumerator GetEnumerator() {
return list.GetEnumerator();
}
}
.
- Follow-Ups:
- References:
- Re: MemberwiseClone() doesn't like arrays?
- From: Xiasma
- Re: MemberwiseClone() doesn't like arrays?
- From: Marc Gravell
- Re: MemberwiseClone() doesn't like arrays?
- From: Ade
- Re: MemberwiseClone() doesn't like arrays?
- Prev by Date: Re: how to decrease the cpu usage
- Next by Date: Certificate information
- Previous by thread: Re: MemberwiseClone() doesn't like arrays?
- Next by thread: Re: MemberwiseClone() doesn't like arrays?
- Index(es):
Relevant Pages
|