Is casting the same thing as converting?

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

    According to Table 1-7 titled "Methods for Explicit Conversion" on page 55 in Chapter 1, Lesson 4 of MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0—Application Development Foundation, there is certainly a difference between them.

    System.Convert is language-independent and converts "Between types that implement the System.IConvertible interface."

    (type) cast operator is a C#-specific language feature that converts "Between types that define conversion operators."

    Furthermore, when implementing custom conversions, advice differs between them.

    Per the section titled How to Implement Conversion in Custom Types on pp. 56-57 in the lesson cited above, conversion operators (casting) are meant for simplifying conversions between numeric types, whereas Convert() enables culture-specific conversions.

    Which technique you choose depends on the type of conversion you want to perform:

    • Define conversion operators to simplify narrowing and widening conversions between numeric types.

    • Implement System.IConvertible to enable conversion through System.Convert. Use this technique to enable culture-specific conversions.

    • ...

    It should be clearer now that since the cast conversion operator is implemented separately from the IConvertible interface, that Convert() is not necessarily merely another name for casting. (But I can envision where one implementation may refer to the other to ensure consistency).

提交回复
热议问题