Is casting the same thing as converting?

前端 未结 11 948
失恋的感觉
失恋的感觉 2020-11-27 17:01

In Jesse Liberty\'s Learning C# book, he says \"Objects of one type can be converted into objects of another type. This is called casting.\"

If you investigate the I

11条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 17:45

    Casting is essentially just telling the runtime to "pretend" the object is the new type. It doesn't actually convert or change the object in any way.

    Convert, however, will perform operations to turn one type into another.

    As an example:

    char caster = '5';
    Console.WriteLine((int)caster);
    

    The output of those statements will be 53, because all the runtime did is look at the bit pattern and treat it as an int. What you end up getting is the ascii value of the character 5, rather than the number 5.

    If you use Convert.ToInt32(caster) however, you will get 5 because it actually reads the string and modifies it correctly. (Essentially it knows that ASCII value 53 is really the integer value 5.)

提交回复
热议问题