Covariance and Contravariance with C# Arrays [duplicate]

房东的猫 提交于 2019-12-01 05:26:35

It's not safe at compile time. In other words, there's code which is legal by the language rules, but fails at execution time, without any explicit casting to give a big warning sign of "this might fail". The CLR makes sure that only valid writes succeed at execution time. For example:

string[] strings = new string[1];
object[] objects = strings;
objects[0] = new object();

That will throw an exception (ArrayTypeMismatchException) at execution time. The alternative would have been to allow it at execution time, at which point strings[0] would have been a reference to a non-string object, which would clearly be bad.

See also recent blog posts:

I think what they're trying to say is:

Dog dog = new Dog();
Cat[] cats = new Cat[] { catOne, catTwo, catThree };
Animal[] animals = cats;
animals.Add(dog);

Line 3 of this code cannot be legal because you SHOULD always be able to do line 4 (Adding a Dog to an array of Animals). But if line 3 was legal, then line 4 would not be legal (because you can't add a Dog to an array of Cats).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!