开发者

Why can't I explicitly cast an int to a string?

开发者 https://www.devze.com 2023-04-02 14:05 出处:网络
If I try to do this it doesn\'t work: static void Main(string[] args) { int a = 5000; Con开发者_如何转开发sole.WriteLine((string)a);

If I try to do this it doesn't work:

static void Main(string[] args)
{
    int a = 5000;
    Con开发者_如何转开发sole.WriteLine((string)a);
}

But somehow this works fine:

static void Main(string[] args)
{
    int a = 5000;
    Console.WriteLine(a + "");
}

Why is that? Is it because the first is trying to change the base type and the second just appends the value to the string?


int cannot be cast to string (1), but there is an operator + that accepts int as left-hand argument and string as right-hand argument (2). This operator converts the int to string and concatenates the two strings.

A better approach would probably be to just use Console.WriteLine(a); which would call a.ToString() for you.


So you are getting a compile time error right? The problem is is that int does not explicitly cast to string.

So

(string)a

is not valid code but

a + ""

mean that the code will work because it basically get translated to

a.ToString() + ""

So the int gets converted into a string value


You should use:

static void Main(string[] args)
{
    int a = 5000;
    Console.WriteLine(a);
}

that implicitly calls a.ToString()


To cast a int in a string you must use int32.parse(string )

That's not right, the parse method of Int32 returns an integer, which is parsed from a string.

To get the string representation of another datatype just use .ToString() from Object Class. Or you use System.Convert.ToString()


That doesn't work because as you have assigned an purely integer value in to a you can not convert it into string by an implicit conversion, but which will work as follows

 static void Main(string[] args)
    {
        int a = 5000;
        Console.WriteLine(a);
    }

which is equal to Console.WriteLine(a.ToString());

0

精彩评论

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