C # implement explicit user-defined type conversion (Keyword: explicit operator)

Source: Internet
Author: User
/*
* Created by sharpdevelop.
* User: noo
* Date: 2009-9-1
* Time:
*
* The predefined Data Types of the system, such as int, float, double, and string, sometimes cannot meet our needs. In this case, we need our own data types, custom Data Type
* However, by default, custom data types cannot be converted from the predefined types in the system. In this case, custom data types do not work at all. Therefore, to use custom data types in the system
* You need to convert the user-defined data type to the data that can be recognized by the system and converted from the predefined data type for use by the system.
*
* Explicit conversion of user-defined types, with the keyword "Explicit". A custom type that can be explicitly converted to the float type is created below.
* In fact, the double type is a type that can be explicitly converted to float. Currently, the created type can be fully considered as a double type.
*/

Using system;
Class mytype // defines its own type, equivalent to float
{
Private float a, B;
Public mytype (float a, float B)
{
This. A =;
This. B = B;
}
Public static explicit operator double (mytype m) // implements the explicit conversion to the double data type method. Pay attention to the modifier and keyword writing here.
{
Return m. A + M. B/10;
}
}
Class Test
{
Static void main ()
{
Mytype Mt = new mytype (12.5f, 6.6f); // equivalent to float Mt = 12.5f
Double D = (double) MT; // here is an explicit conversion, equivalent to double D = (double) Mt
Console. writeline (d); // output 13.1599999904633
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.