-2
只是想了解C#。只是考慮下面的簡單例子。爲什麼這種隱式轉換不會導致編譯時錯誤?
void Main()
{
IList<IAnimal> animals = new List<IAnimal>
{
new Chicken(),
new Cow(),
};
// Shouldn't this line result in a compile-time error?
foreach (Chicken element in animals)
{
}
}
public interface IAnimal
{
}
public class Cow : IAnimal
{
}
public class Chicken : IAnimal
{
}
儘管第一次迭代成功,但第二次迭代沒有成功。老實說,我預計這會在編譯時失敗。有誰知道它爲什麼只在運行時失敗?
[回覆Eric Lippert](http://ericlippert.com/2013/07/22/why-does-a-foreach-loop-silently-insert-an-explicit-conversion/) –
另請參閱:[爲什麼foreach循環默默插入「顯式」轉換?](http://ericlippert.com/2013/07/22/why-does-a-foreach-loop-silently-insert-an-explicit-conversion/)由Eric Lippert – Habib
有人鏈接Eric Lippert關於此的帖子呢? – CodeCaster