Is casting the same thing as converting?

前端 未结 11 964
失恋的感觉
失恋的感觉 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

    Semantics aside, a quick test shows they are NOT equivalent !
    They do the task differently (or perhaps, they do different tasks).

    x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2
    x=-1.5 (int)x=-1 Convert.ToInt32(x)=-2
    x=-0.5 (int)x= 0 Convert.ToInt32(x)= 0
    x= 0.5 (int)x= 0 Convert.ToInt32(x)= 0
    x= 1.5 (int)x= 1 Convert.ToInt32(x)= 2
    x= 2.5 (int)x= 2 Convert.ToInt32(x)= 2
    

    Notice the x=-1.5 and x=1.5 cases.

提交回复
热议问题