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

前端 未结 7 1346
感动是毒
感动是毒 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:18

    With VS 2008, I am not getting this warning. This must be new to .NET 4.0.
    Clarification: according to Sam Mackrill it's Resharper who displays a warning.

    The C# compiler does not know that AddRange will not modify the array passed to it. Since AddRange has a parameter of type Control[], it could in theory try to assign a TextBox to the array, which would be perfectly correct for a true array of Control, but the array is in reality an array of LinkLabels and will not accept such an assignment.

    Making arrays co-variant in c# was a bad decision of Microsoft. While it might seem a good idea to be able to assign an array of a derived type to an array of a base type in the first place, this can lead to runtime errors!

提交回复
热议问题