考慮代碼片段。通用協方差和反變量
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>
和ICollection<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);
}
@ dlev.Could you please please more more.I'numerable'IEnumerable'covariant and'ICollection 'does not。 –
@Ashely剛剛更新了我的答案與該信息。 – dlev