tailieunhanh - My Double Method
Understanding Conversion Operators Sometimes it is necessary to convert an expression of one type into another. For example, the following method is declared with a single double parameter | Understanding Conversion Operators Sometimes it is necessary to convert an expression of one type into another. For example the following method is declared with a single double parameter class Example public static void MyDoubleMethod double parameter . You might reasonably expect that only values of type double could be used as arguments when calling MyDoubleMethod but this is not so. The C compiler also allows MyDoubleMethod to be called with an argument whose type is not double but only as long as that value can be converted to a double. The compiler will generate code that performs this conversion when the method is called. Providing Built-In Conversions The built-in types have some built-in conversions. For example an int can be implicitly converted to a double. An implicit conversion requires no special syntax and never throws an exception 42 implicit int to double conversion An implicit conversion is sometimes called a widening conversion as the result is wider than the original value it contains at least as much information as the original value and nothing is lost. On the other hand a double cannot be implicitly converted to an int class Example public static void MyIntMethod int parameter . . compile-time error Converting from a double to an int runs the risk of losing information so it will not be done automatically consider what would happen if the argument to MylntMethod was how should this be converted A double can be converted to an int but the conversion requires an explicit notation a cast int An explicit conversion is sometimes called a narrowing conversion as the result is narrower than the original value it can contain less information and can throw an OverflowException. C allows you to provide conversion operators for your own user-defined types to control whether they can be implicitly or explicitly converted to other types. Implementing User-Defined Conversion .
đang nạp các trang xem trước