-1

私はC#にまったく慣れていません。配列内の文字列要素が Web サイト検索の最後に配置される短い配列をループしようとしています。コード:

int n = 1;
string[] s = {"firstitem","seconditem","thirditem"}
int x = s.Max(); // note, from my research this should return the maximum value in the array, but this is the first error
x = x + 1

while (n < x)
{

      System.Diagnostics.Process.Start("www.website.com/" + b[0]);

      b[]++; // this also generates an error "identifier expected"

}

私のコーディング、ロジック、またはその両方が間違っています。私が読んだことに基づいて、配列の最大値を(intとして)取得し、配列の値に追加し、WHILEループがWebサイトの最後に配列の各値を追加できるはずです(そして止まります)。最初のエラーで、以下のように別の方法でコーディングしようとしたことに注意してください。

int x = Convert.ToInt32(s.Max);

ただし、過負荷エラーが発生します。私が物事を正しく読んでいればMAX、シーケンスの最大値を見つける必要があります。

4

5 に答える 5

3

文字列のコレクションがあります。最大の文字列は引き続き文字列であり、int ではありません。は文字列なのでs.Max()、それを int 型の変数に割り当てています。int x = s.Max();コンパイラは (正しく) 型が一致しないことを通知します。その文字列を int に変換する必要があります。あなたのデータを見ると、それらは整数ではなく、これらの文字列を整数に変換する賢明な方法がわからないため、合理的な解決策はありません。"firstitem" はどのような整数にする必要がありますか?

配列内の各項目に対してコードを実行するだけの場合は、次のパターンのいずれかを使用します。

foreach(string item in s)
{
    System.Diagnostics.Process.Start("www.website.com/" + item);
}

また

for(int i = 0; i < s.Length; i++)
{
    System.Diagnostics.Process.Start("www.website.com/" + s[i]);
}
于 2013-04-25T21:14:10.513 に答える
1

以下は、コードのエラーを指摘するための画像です。

写真で答える

修正後は次のようになります。

int n=1;
string[] s= { "firstitem", "seconditem", "thirditem" };
int x=s.Length;

while(n<x) {
    System.Diagnostics.Process.Start("www.website.com/"+s[n]);
    n++; // or ++n
}

そして、それをより意味的にすることができます:

var items=new[] { "firstitem", "seconditem", "thirditem" };

for(int index=1, count=items.Length; index<count; ++index)
    Process.Start("www.website.com/"+items[index]);

開始順序が重要ではforeachなく、代わりに使用でき、Linq を使用してコードをさらに単純にすることができる場合:

var list=(new[] { "firstitem", "seconditem", "thirditem" }).ToList();
list.ForEach(item => Process.Start("www.website.com/"+item));

また、別の形式で書くこともよくあります。

foreach(var item in new[] { "firstitem", "seconditem", "thirditem" })
    Process.Start("www.website.com/"+item);
于 2013-04-25T21:53:44.480 に答える