我试图模拟这个 ReadOnlyCollection 属性:
private readonly IList<MyClass> myList = new List<MyClass>();
public virtual ReadOnlyCollection<MyClass> MyList
{
get
{
return new ReadOnlyCollectionBuilder<MyClass>(this.myList).ToReadOnlyCollection();
}
}
使用这个模拟(如此处所示):
IList<MyClass> mockList = GetElements();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.myList).Returns(mockList);
但是在运行时我得到一个 InvalidCastException:
Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.
我究竟做错了什么?