-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 的结果类型是 string 并且 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 正在返回您尝试分配给 integer 的字符串j

  2. 你的 j 是整数。如何用 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

您必须使用显式类型转换。

采用

int i = Convert.ToInt32(aString);

转换。

于 2012-07-03T19:29:52.473 回答