Created
February 24, 2021 12:44
-
-
Save sandrock/e0477b2bff576dba541197c4ecee08ae to your computer and use it in GitHub Desktop.
C# CollectionProxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace SrkToolkit.Common | |
{ | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
/// <summary> | |
/// Proxies a collection of <typeparamref name="TSource"/> into a collection of <typeparamref name="T"/> using a direct cast mehod. | |
/// </summary> | |
/// <typeparam name="TSource">source collection item type</typeparam> | |
/// <typeparam name="T">new collection item type</typeparam> | |
public class CollectionProxy<TSource, T> : IList<T> | |
where TSource : T | |
{ | |
private readonly IList<TSource> source; | |
public CollectionProxy(IList<TSource> source) | |
{ | |
this.source = source; | |
} | |
public T this[int index] | |
{ | |
get { return this.ToTarget(this.source[index]); } | |
set { this.source[index] = this.ToSource(value); } | |
} | |
public int Count | |
{ | |
get { return this.source.Count; } | |
} | |
public bool IsReadOnly | |
{ | |
get { return this.source.IsReadOnly; } | |
} | |
public void Add(T item) | |
{ | |
this.source.Add(this.ToSource(item)); | |
} | |
public void Clear() | |
{ | |
this.source.Clear(); | |
} | |
public bool Contains(T item) | |
{ | |
return this.source.Contains(this.ToSource(item)); | |
} | |
public void CopyTo(T[] array, int arrayIndex) | |
{ | |
throw new NotSupportedException(); | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return (IEnumerator<T>)this.source.GetEnumerator(); | |
} | |
public int IndexOf(T item) | |
{ | |
return this.source.IndexOf(this.ToSource(item)); | |
} | |
public void Insert(int index, T item) | |
{ | |
this.source.Add(this.ToSource(item)); | |
} | |
public bool Remove(T item) | |
{ | |
return this.source.Remove(this.ToSource(item)); | |
} | |
public void RemoveAt(int index) | |
{ | |
this.source.RemoveAt(index); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return this.source.GetEnumerator(); | |
} | |
private TSource ToSource(T item) | |
{ | |
return (TSource)item; | |
} | |
private T ToTarget(TSource item) | |
{ | |
return (T)item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment