Co-variant array conversion from x to y may cause run-time exception

前端 未结 7 1396
感动是毒
感动是毒 2020-12-23 15:37

I have a private readonly list of LinkLabels (IList). I later add LinkLabels to this list and add those

7条回答
  •  情话喂你
    2020-12-23 16:08

    What it means is this

    Control[] controls = new LinkLabel[10]; // compile time legal
    controls[0] = new TextBox(); // compile time legal, runtime exception
    

    And in more general terms

    string[] array = new string[10];
    object[] objs = array; // legal at compile time
    objs[0] = new Foo(); // again legal, with runtime exception
    

    In C#, you are allowed to reference an array of objects (in your case, LinkLabels) as an array of a base type (in this case, as an array of Controls). It is also compile time legal to assign another object that is a Control to the array. The problem is that the array is not actually an array of Controls. At runtime, it is still an array of LinkLabels. As such, the assignment, or write, will throw an exception.

提交回复
热议问题