我有以下代码:
public interface ISomeObject
{
IList<ISomeObject> Objects { get; }
}
public class SomeObject : ISomeObject
{
public SomeObject()
{
Objects = new List<SomeObject>();
}
public List<SomeObject> Objects
{
get;
set;
}
IList<ISomeObject> ISomeObject.Objects
{
get
{
// What to do here?
// return Objects; // This doesn't work
return Objects.Cast<ISomeObject>().ToList(); // Works, but creates a copy each time.
}
}
SomeObject
具有一个公共属性Objects
,该属性返回类类型的列表。知道该类类型的客户可以使用它来做他们想要的任何事情。仅了解ISomeObject
的客户端只能使用Objects
属性来获取IList<ISomeObject>
。因为不允许将List<SomeObject>
强制转换为IList<ISomeObject>
(由于apple and banana issue),所以我需要一种转换方法。使用Cast.ToList()的默认方式有效,但缺点是每次评估属性时都会创建一个新List,这可能会很昂贵。更改ISomeObject.Objects
以返回IEnumerable<ISomeObject>
的另一缺点是客户端无法再使用索引(这在我的用例中非常相关)。在IEnumerable上重复使用Linq的ElementAt()调用很昂贵。有谁知道如何避免这两个问题?
(当然,让
SomeObject
到处都是已知的不是一种选择)。 最佳答案
您可以/应该实现类似于ReadOnlyCollection<T>
的类来充当代理。考虑到它将是只读的,因此它可以是“协变的”(不是语言方面的,而是逻辑上的含义,这意味着它可以代理作为TDest
的子类/接口的TSource
),然后对所有写方法。
像这样的东西(未经测试的代码):
public class CovariantReadOlyList<TSource, TDest> : IList<TDest>, IReadOnlyList<TDest> where TSource : class, TDest
{
private readonly IList<TSource> source;
public CovariantReadOlyList(IList<TSource> source)
{
this.source = source;
}
public TDest this[int index] { get => source[index]; set => throw new NotSupportedException(); }
public int Count => source.Count;
public bool IsReadOnly => true;
public void Add(TDest item) => throw new NotSupportedException();
public void Clear() => throw new NotSupportedException();
public bool Contains(TDest item) => IndexOf(item) != -1;
public void CopyTo(TDest[] array, int arrayIndex)
{
// Using the nuget package System.Runtime.CompilerServices.Unsafe
// source.CopyTo(Unsafe.As<TSource[]>(array), arrayIndex);
// We love to play with fire :-)
foreach (TSource ele in source)
{
array[arrayIndex] = ele;
arrayIndex++;
}
}
public IEnumerator<TDest> GetEnumerator() => ((IEnumerable<TDest>)source).GetEnumerator();
public int IndexOf(TDest item)
{
TSource item2 = item as TSource;
if (ReferenceEquals(item2, null) && !ReferenceEquals(item, null))
{
return -1;
}
return source.IndexOf(item2);
}
public void Insert(int index, TDest item)
{
throw new NotSupportedException();
}
public bool Remove(TDest item)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
像这样使用它:
IList<string> strs = new List<string>();
IList<object> objs = new CovariantReadOlyList<string, object>(strs);