C # Programming (41)----------user-defined data type conversions

Source: Internet
Author: User

User-defined data type conversions

C # allows you to define your own data types , which means that some tools are required to support data conversion between your own data types . The method is to define a data type conversion as a member operator of a related class , and the data type conversion must be declared either implicitly or explicitly to illustrate how it is used .

C # allows the user to make two defined data type conversions , explicitly and implicitly , explicitly requiring explicit markup conversions in code by writing the target data type in the original brackets .

For predefined data types , when data type conversions may fail or data is lost, the conversion needs to be displayed :

1. Convert the int value to short , because short may not be large enough to contain the converted value .

2. Convert the data of all symbols to unsigned data , and if the signed variable contains a negative value , the result will be incorrect.

3. When converting a floating-point number to an integer data type , the fractional part of the digit is lost .

You should display the data type conversions in your code , telling the compiler that you know that there is a risk of losing data , so you can take these into account when writing your code .

Note : data type conversions should be defined as explicit If the source data value causes the data conversion to fail, or if an exception may be thrown.

The syntax for defining data type conversions is somewhat similar to operator overloading .

For example, the code for an implicit type conversion :

public static inplicit operator float

{}

As with operator overloading , data type conversions must be declared public and static.

Note :

When a data type conversion is declared as implicit , the compiler can call data type conversions either explicitly or implicitly .

When a data type conversion is declared explicit , the compiler can only explicitly invoke type conversions .

Case :

Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

Using System.Threading.Tasks;

namespace type Conversions

{

Class Program

{

static void Main (string[] args)

{

Try

{

Current balance = new Current (50, 35);

Console.WriteLine (balance);

Console.WriteLine ("Balance Using ToString (): +" + balance. ToString ());

Implicit type conversions

float Balance2 = balance;

Console.WriteLine ("After converting to float:" + balance2);

Display Type Conversions

Balance = (current) Balance2;

Console.WriteLine ("After converting to current:" + balance);

float T = 45.63f;

Current C = (current) t;

Console.WriteLine (C.tostring ());

Checked

{

Balance = (current) (-50.5);

Console.WriteLine ("Result is:" + balance. ToString ());

}

}

catch (Exception)

{

Console.WriteLine (" error ");

}

Console.readkey ();

}

}

struct current

{

public UINT Dollars;

public ushort Cents;

constructor Function

Public current (UINT dollars, ushort cents)

{

This. Dollars = Dollars;

This. Cents = Cents;

}

overriding the ToString () method

public override string ToString ()

{

return string. Format ("{0}.{ 1,-2:00} ", this. Dollars, this. Cents);

}

Implicit type conversions

public static implicit operator float (current value)

{

return value. Dollars + (value. cents/100.0f);

}

Display Type Conversions

public static explicit operator current (float f)

{

UINT dollars = (uint) F;

USHORT cents = (ushort) ((f-dollars) * 100);

return new current (dollars, cents);

}

}

}

Two questions will be designed :

1. A truncation problem occurs when converting from float to current to get the wrong result 50.34 instead of 50.35,---- rounding .

For:IfFloatValue is converted toUIntValue,The computer will truncate the extra digits.,Instead of rounding it..The computer data is stored through the binary,Instead of the decimal, small part 0.35 can not be stored in binary form . Because part of the ,0.35, The value that can be stored in binary form , Then multiply the numbers by 100, get less than 3534, Sometimes this stage is dangerous. Span style= "Font-family:times New Roman" >, Avoid this wrong way when making sure to perform intelligent rounding operations during the digital conversion

Microsoft has written a class System.Convert to complete the task . System.Convert contains a number of static methods to perform various digital conversions , and we want to use convert.touint16 (). Note that the use of the System.Convert method generates additional performance losses , so it is only used when needed .

Note : The System.Convert method also performs their own overflow check , so

Convert.touint16 ((f-dollars) *100);

Such code can not be placed inside the checked .

2. When attempting to convert values out of range , no exception . : The location where the overflow occurred is not at all main-- This is what happens in the code of the conversion operator. , The code in Main () method calls This method is not marked as checked, :

Code :

public static explicit operator current (float f)

{

Checked

{

UINT dollars = (uint) F;

UShort cents = convert.touint16 ((f-dollars) * 100);

return new current (dollars, cents);

}

}

Explicit and implicit belong to the conversion operator , the two of which allow us to customize the type to support mutual Exchange

Explicit represents the display transformation , which must be cast from A->b : b= (B) A

Implicit represents an implicit conversion b->a just copy a=b

Implicit conversions can make our code look prettier and move more succinctly, so it's best to use the implicit operator more . However , if the object itself loses some information (such as precision) when it is converted, then we can only use the explicit operator so that at compile time we can warn the client to call .

C # Programming (41)----------user-defined data type conversions

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.