Convert char to int in C#

后端 未结 14 810
情深已故
情深已故 2020-11-22 10:44

I have a char in c#:

char foo = \'2\';

Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value o

相关标签:
14条回答
  • 2020-11-22 11:26

    Has anyone considered using int.Parse() and int.TryParse() like this

    int bar = int.Parse(foo.ToString());
    

    Even better like this

    int bar;
    if (!int.TryParse(foo.ToString(), out bar))
    {
        //Do something to correct the problem
    }
    

    It's a lot safer and less error prone

    0 讨论(0)
  • 2020-11-22 11:26

    The real way is:

    int theNameOfYourInt = (int).Char.GetNumericValue(theNameOfYourChar);

    "theNameOfYourInt" - the int you want your char to be transformed to.

    "theNameOfYourChar" - The Char you want to be used so it will be transformed into an int.

    Leave everything else be.

    0 讨论(0)
提交回复
热议问题