C # Explicit and implicit

Source: Internet
Author: User

explicit and implicit are used to declare user-defined type conversion operators , and if you can ensure that the conversion process does not result in data loss, you can use these two keywords to convert between a user-defined type and another type.

Explicit (Explicit, obvious: explicit)

Implicit (implied, implied: implicit)

1. What problems do they solve?

Consider the following requirements, the person class has a field of age. What if I want to create a person object with age 18 using person P = (person) 18来?

Further, I want to use person P = 18来 to create a person object with age 18, what should I do?

2, using explicit (explicit) and implicit (implicit)

classperson{Private intAge Public intAge {get {returnAge } set {age =value; }    } Public Static Explicit operatorPerson (intAge) {return NewPerson () {age = Age,}; }//public static implicit operator person (int.)    //{    //return new person () {age = Age,};    //}}classprogram{Static voidMain (string[] args) {person p = (person) 18;//Call explicit        //person p = 18;//Call implicit}}

Note: Neither can be provided at the same time, or compile errors. This syntax is in fact borrowed from the C + + approach, and has been extended. In general, do not use this type of conversion because it is not intuitive.

Reference: Https://msdn.microsoft.com/zh-cn/library/z5z9kes2.aspx

Http://www.cnblogs.com/nzbbody/p/3519688.html

C # Explicit and implicit

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.