考虑代码片段。
IList<String> obj=new List<string>();
IEnumerable<Object> obj1 = obj;
但是如果我写ICollection<Object> obj2 = obj;
它会给我一个编译时错误。
无法将类型“
System.Collections.Generic.IList<string>
”隐式转换为“System.Collections.Generic.ICollection<object>
”。
为什么这种行为既然List<T>
实现了IEnumerable<T>
andICollection<T>
并且也IList<T>
被定义为
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
T this[int index] { get; set; }
int IndexOf(T item);
void Insert(int index, T item);
void RemoveAt(int index);
}