如何将字符串转换为int?

问题描述:

可能重复:
How can I convert String to Int?如何将字符串转换为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()); 

我收到提示说:

无法隐式转换类型“字符串”到“廉政”

现在GetKey功能是字符串类型:

public string GetKey(string key) 
{ 
} 

我该怎么办?

+0

此问题询问有关将int转换为字符串的问题,但您已经想清楚了,并且该错误消息是关于将字符串转换为int的。 – hvd

+3

请修改您的问题并更正其标题。问题是关于字符串到整数转换,而不是整数到字符串。 – daniloquio

+1

我喜欢大多数正确的答案是downvoted。 – jrummell

您的信息getKey的结果类型为字符串连接第j个变量声明INT

的解决方案是:

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

我希望这是解决你的问题。

试试这个:

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

如果该值不是有效的整数它会抛出异常。

另一种是TryParse,如果转换不成功返回boolean:

j = 0; 

Int32.TryParse(GetKey((keys + i).ToString()), out j); 
// this returns false when the value is not a valid integer. 

的问题是,“J”是一个int,且将其分配给信息getKey的回报。使“j”成为一个字符串,或将GetKey的返回类型更改为int。

What should i do ? 

你一切都错了。阅读关于值类型和引用类型。

错误:

  1. 错误是Cannot implicitly convert type 'string' to 'int'。隐含的含义是获得一个不能转换为int的字符串。 GetKeys返回字符串,您试图将其分配给整数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; 
} 
+5

“学习一些编程”是不必要的和粗鲁的。我们都从某个地方开始,我们需要的最后一件事就是让我们在寻求帮助时轻视我们。 – DarLom

+0

@DarvisLombardo:更正。采取的点。反向Downvote。 –

+0

@daniloquio:我想要+10。但我不会那么做。我当前的限制为200天。 –

你必须使用一个exppicit类型转换。

使用

int i = Convert.ToInt32(aString); 

转换。

+0

这是Java,而不是C#。 – hvd

+0

1.他想将int转换为字符串2.这是一个C#问题。 – Femaref

+2

@Femaref re。 1:不,他没有。问题标题是错误的,错误信息是关于字符串到整数转换。 – hvd

您正在接收错误,因为GetKey返回一个字符串,并且您试图将返回对象指定给j,并将其声明为int。您需要按照alfonso的建议进行操作,并将返回值转换为int。您还可以使用:

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

尝试改进代码,看看这个:

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; 
} 

我希望它帮你! :)