Guide to the Language
CHAPTER 23 Custom Conversions
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Implicit Conversion Methods
- Explicit Conversion Methods
CHAPTER 23
Custom Conversions This chapter covers how to define custom type conversions for an object. As seen in the following example, a class called MyNum is created with a single int field and a constructor. With a custom type conversion, it becomes possible to allow an int to be implicitly converted to an object of this class. class MyNum { public int val; public MyNum(int i) { val = i; } } Implicit Conversion Methods For this to work, an implicit conversion method needs to be added to the class. This method’s signature looks similar to that used for unary operator overloading. It must be declared as public static and includes the operator keyword. However, instead of an operator symbol the return type is specified, which is the target type for the conversion. The single parameter will hold the value that is to be converted. The implicit keyword is also included, which specifies that the method is used to perform implicit conversions. 136 public static implicit operator MyNum(int a) { return new MyNum(a); } With this method in place, an int can be implicitly converted to a MyNum object. MyNum a = 5; // implicit conversion Another conversion method can be added that handles conversions in the opposite direction, from a MyNum object to an int. public static implicit operator int(MyNum a) { return a.val; } Explicit Conversion Methods To prevent potentially unintended object type conversions by the compiler, the conversion method can be declared as explicit instead of implicit. public static explicit operator int(MyNum a) { return a.val; } The explicit keyword means that the programmer has to specify an explicit cast in order to invoke the type conversion method. In particular, explicit conversion methods should be used if the result of the conversion leads to loss of information, or if the conversion method may throw exceptions. MyNum a = 5; int i = (int)a; // explicit conversion Chapter 23 Custom Conversions 137 © Mikael Olsson 2020 M. Olsson, C# 8 Quick Syntax Reference, https://doi.org/10.1007/978-1-4842-5577-3_24 Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling