开发者

Need an easy way to change my string into an integer in c#

I have a string like this:

var myString = "025"

Is there an easy way to chan开发者_开发百科ge this to a number?


int myNumber = int.Parse(myString);

Note that this will throw an exception if myString cannot be converted to an int. You can use TryParse instead that is safer

int myNumber
if( int.TryParse(myString, out myNumber){
  //conversion ok, and myNumber now contains the int
}else{
  //conversion failed. myNumber will now be 0.
}


You could do

string str = "123";
int value = int.MinValue;

if(int.TryParse(str, out value))
 MessageBox.Show("Successfully parsed");
else
   MessageBox.Show("Parsing failed");


var myInt = Int32.Parse(myString);

Although for these kind of questions, I think reading a book and discovering the language would do some good.


Also it is possible to use:

int value = Convert.ToInt32("myString");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜