从X到Y联合变量数组转换可能会导致运行时异常可能会、数组、变量、异常

2023-09-07 11:55:45 作者:‖突然七年似尘埃

我有一个私人只读列表的LinkLabel S(的IList< LinkLabel的> )。我后来的LinkLabel S添加到这个列表,并添加这些标签到 FlowLayoutPanel的类似如下:

 的foreach(VAR S在弦)
{
    _list.Add(新的LinkLabel的{text = S});
}

flPanel.Controls.AddRange(_list.ToArray());
 

ReSharper的显示了我一个警告:从LinkLabel的[] 联合变量数组转换到控制[]可以在写入操作导致运行时异常。

请帮我弄清楚:

这是什么意思? 这是一个用户控件,并且不会被多个对象设置标签的访问,  因此保持code因为这样会不会影响它。 解决方案

它的意思是这个

 控制[] =控制新的LinkLabel [10]; //编译时的法律
对照组[0] =新文本框(); //编译时合法的,运行时异常
 
机器学习基础 1

和在更普通的术语

  String []数组=新的字符串[10];
[对象] OBJ文件=阵列; //合法在编译时
OBJ文件[0] =新的Foo(); //再次法律,与运行时异常
 

在C#中,被允许引用对象的数组(你的情况,LinkLabels),为基本类型的阵列(在此情况下,作为控制的阵列)。这也是编译时的法律来分配的另一个的对象,它是一个控制到阵列。问题是,该阵列的实际上不是控件的阵列。的在运行时,它仍然是LinkLabels的阵列。因此,转让,或写,会抛出异常。

I have a private readonly list of LinkLabels (IList<LinkLabel>). I later add LinkLabels to this list and add those labels to a FlowLayoutPanel like follows:

foreach(var s in strings)
{
    _list.Add(new LinkLabel{Text=s});
}

flPanel.Controls.AddRange(_list.ToArray());

Resharper shows me a warning: Co-variant array conversion from LinkLabel[] to Control[] can cause run-time exception on write operation.

Please help me to figure out:

What does this means? This is a user control and will not be accessed by multiple objects to setup labels, so keeping code as such will not affect it.

解决方案

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.