C# 我有四个WebBrowser,每个名为web1、web2等。。。如何为它们使用for循环?
我有一个for循环和四个webbrowser。它们被称为:C# 我有四个WebBrowser,每个名为web1、web2等。。。如何为它们使用for循环?,c#,for-loop,C#,For Loop,我有一个for循环和四个webbrowser。它们被称为: Web1 Web2 Web3 Web4 我有一个for循环: for (int i = 1; i <= 4; i++) 然而,这些产出: The name "web" does not exist in the current context 我该怎么做?使用数组 var webBrowsers = new[] { Web1, Web2, Web3, Web4 }; for(int i = 0; i < webBr
- Web1
- Web2
- Web3
- Web4
for (int i = 1; i <= 4; i++)
然而,这些产出:
The name "web" does not exist in the current context
我该怎么做?使用数组
var webBrowsers = new[] { Web1, Web2, Web3, Web4 };
for(int i = 0; i < webBrowsers.Length; i++)
{
webBrowsers[i]... // Do something with each
}
var webBrowsers=new[]{Web1、Web2、Web3、Web4};
对于(int i=0;i
一般来说,只要变量具有序列名(如Web1
。Web4
),就很好地表明您可能应该使用数组。就我个人而言,我会重构代码,以便删除对单个webBrowser
控件的所有引用,并专门使用数组。然而,这可能超出了这个问题的范围
进一步阅读:
var matches = this.Controls.Find(string.Format("Web{0}", i), true);
// this means you can't find that control
if (matches.Length == 0) { continue; }
// now you can cast the first control if you'd like
var web = matches[0] as WebBrowser;
顺便问一下,我是否会在C#中使用@Minicl55数组以0为基数,这意味着对于4元素数组,有效索引是0、1、2和3
webBrowsers.Length
将返回4(有4个元素),但i
必须在3处停止,否则将出现范围异常。啊,我以为它将返回3而不是4
var matches = this.Controls.Find(string.Format("Web{0}", i), true);
// this means you can't find that control
if (matches.Length == 0) { continue; }
// now you can cast the first control if you'd like
var web = matches[0] as WebBrowser;