简体   繁体   English

为什么Find()方法返回一个数组?

[英]Why does the Find() method return an array?

I want to locate a TextBox named "textBoxQH_N" where "_N" is a number from 1..96. 我想找到一个名为“textBoxQH_N”的TextBox,其中“_N”是1..96的数字。

So, I've got this code: 所以,我有这个代码:

String sTextBoxToFind = String.Format("textBoxQH{0}", QuarterHour);
TextBox tb = (TextBox)this.Controls.Find(sTextBoxToFind, true);

...but it gave me, " Cannot convert type 'System.Windows.Forms.Control[]' to 'System.Windows.Forms.TextBox' " ...但它给了我,“ 无法将类型'System.Windows.Forms.Control []'转换为'System.Windows.Forms.TextBox'

So I changed the second line to grab just the first returned val: 所以我更改了第二行以获取第一个返回的val:

TextBox tb = (TextBox)this.Controls.Find(sTextBoxToFind, true)[0];

Which seems to work, but shouldn't a Control's Name property be unique to its owner? 这看起来有效,但是控件名称属性不应该是其所有者独有的吗? IOW, Find() should only return 0..1 controls, right? IOW,Find()应该只返回0..1控件,对吗?

Find , with the second property set to true, is recursive. Find ,第二个属性设置为true,是递归的。 'Name' is unique to that parent, but you're searching through lots of different parents. “姓名”对于该父母来说是独一无二的,但您正在搜索许多不同的父母。 'Name' isn't globally unique. “名称”不是全球唯一的。

As suggested by Justin in another answer, First or FirstOrDefault is probably better than using [0] on the array. 正如Justin在另一个答案中所建议的那样, FirstFirstOrDefault可能比在数组上使用[0]更好。 It does a better job of conveying your intentions to future readers. 它可以更好地将您的意图传达给未来的读者。

The Find method will find any matches, so even though it is only one match in your case, it could be numerous in other cases. Find方法将找到任何匹配项,因此即使在您的情况下它只是一个匹配项,在其他情况下也可能很多。 You could probably use LINQ First here if you wanted something more semantically meaningful? 如果你想要更具语义意义的东西,你可以在这里使用LINQ First吗?

The MSDN on this is pretty clear on this method MSDN对此方法非常清楚

It returns an array of Controls. 它返回一组控件。 try it like: 试试看:

Control[] tb = this.Controls.Find("textBox1", true); //change the name of the control

or: 要么:

TextBox[] tbs = (TextBox[])this.Controls.Find("tb1", true);

As you can see, you must CAST to the correct type of object (in your case to array of TextBoxes). 如您所见,您必须CAST到正确类型的对象(在您的情况下为TextBoxes数组)。 Hope it helps, bye 希望它有所帮助,再见

Form API design point of view 0 and 1 choices are better to be returned as IEnumerable/collection/array to avoid need for null checks. 从API设计的角度来看,0和1选择最好作为IEnumerable / collection / array返回,以避免需要进行空检查。

As pointed by other answers, Name of control does not have to be globally unique and Find actually may return more than 1 item. 正如其他答案所指出的,控件名称不必是全局唯一的,而实际上查找可能返回多于1个项目。

Link to MSDN - Controls.Find 链接到MSDN - Controls.Find

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM