c# - 高效返回 IList来自列表(避免从列表中投射列出)
问题描述
解决方案
您可以/应该实现一个类似于ReadOnlyCollection<T>
充当代理的类。考虑到它是只读的,它可以是“协变的”(不是语言方面的,而是逻辑上的,这意味着它可以代理 aTDest
作为 的子类/接口TSource
),然后throw NotSupportedException()
是所有的 write 方法。
像这样的东西(代码未经测试):
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);
推荐阅读
- c++ - 构造函数中的变量未在此范围内声明 c++
- r - R - 当数据有变量时导出到 xlsx 是一个列表
- kubernetes - 如何在 Kubernetes 中对不受信任的代码进行沙箱处理
- flutter - 有没有办法替换字符串中的多个关键字并用自己的关键字包装它们?
- android - 颤振构建失败
- node.js - Imgur上传api错误总是用multer和form-data nodejs返回400
- types - 如何在 Rust 中通过 `T`、`&T` 和 `&mut` T 获得相同的 `std::any::TypeId::of` 结果?
- c# - File.CreateText 在某些环境中编码为 UTF-8,但在其他环境中编码为 UTF-8 和 BOM
- java - 你能解释一下这个解决方案有什么区别吗
- html - 显示嵌套下拉菜单,溢出隐藏设置为父下拉菜单