-3

重複の可能性:
String を Int に変換するにはどうすればよいですか?

public List<int> GetListIntKey(int keys)
{
        int j;
        List<int> t;
        t = new List<int>();
        int i;
        for (i = 0; ; i++)
        {
            j = GetKey((keys + i).ToString());
            if (j == null)
            {
                break;
            }
            else
            {
                t.Add(j);
            }
        }
        if (t.Count == 0)
            return null;
        else
            return t;
}

問題は次の行にあります。

j = GetKey((keys + i).ToString());

エラーが表示されます:

タイプ 'string' を 'int' に暗黙的に変換することはできません

今、GetKey関数は文字列の型です:

public string GetKey(string key)
{
}

私は何をすべきか ?

4

7 に答える 7

5

問題は、「j」が int であり、それを GetKey の戻り値に割り当てていることです。「j」を文字列にするか、GetKey の戻り値の型を int に変更してください。

于 2012-07-03T19:28:03.357 に答える
3

これを試して:

j = Int32.Parse(GetKey((keys + i).ToString()));

値が有効な整数でない場合、例外がスローされます。

代替手段はTryParse、変換が成功しなかった場合にブール値を返す です。

j = 0;

Int32.TryParse(GetKey((keys + i).ToString()), out j);
// this returns false when the value is not a valid integer.
于 2012-07-03T19:27:55.370 に答える
2

getkey の結果の型は文字列 en であり、j 変数は int と宣言されています

解決策は次のとおりです。

j = Convert.ToInt32(GetKey((keys + i).ToString()));

これがあなたの問題の解決策であることを願っています。

于 2012-07-03T19:32:19.790 に答える
1

GetKey が文字列を返し、戻りオブジェクトを int として宣言されている j に割り当てようとしているため、エラーが発生しています。アルフォンソが提案したようにして、戻り値をintに変換する必要があります。以下も使用できます。

j = Convert.ToInt32(GetKey((keys+i).ToString()));
于 2012-07-03T19:35:02.190 に答える
1

コードを改善してみてください。

public List<int> GetListIntKey(int keys)
{
    var t = new List<int>();

    for (int i = 0; ; i++)
    {
        var j = GetKey((keys + i).ToString());
        int n;
        // check if it's possible to convert a number, because j is a string.
        if (int.TryParse(j, out n))
            // if it works, add on the list
            t.Add(n);
        else //otherwise it is not a number, null, empty, etc...
            break;
    }
    return t.Count == 0 ? null : t;
}

お役に立てば幸いです。:)

于 2012-07-03T19:35:11.743 に答える
-1
What should i do ?

あなたはそれをすべて間違っています。値型と参照型について読んでください。

エラー:

  1. エラーはCannot implicitly convert type 'string' to 'int'です。暗黙のうちに、intに変換できない文字列を取得していることを意味します。GetKeys は、整数に割り当てようとしている文字列を返しますj

  2. あなたの j は整数です。nullでどのように確認できますか。値の型を null にできるのはいつですか?

これを使って

public List<int> GetListIntKey(int keys)
{
    int j = 0;
    List<int> t = new List<int>();
    for (int i = 0; ; i++)
    {
        string s = GetKey((keys + i).ToString());

        if (Int.TryParse(s, out j))
            break;
        else
            t.Add(j);
    }

    if (t.Count == 0)
        return null;
    else
        return t;
}
于 2012-07-03T19:28:39.370 に答える
-1

exppicit 型キャストを使用する必要があります。

使用する

int i = Convert.ToInt32(aString);

変換する。

于 2012-07-03T19:29:52.473 に答える