C # Explicit and implicit

Source: Internet
Author: User

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)

1 class Person2     {3         Private intAge ;4          Public int Age5         {6             Get{returnAge ;}7             Set{age =value;}8         }9 Ten          Public Static Explicit operatorPerson (intAge ) One         { A             return NewPerson () {age =Age ,}; -         } -  the         //Public static implicit operator person (int.) -         //{ -         //return new Person () {age = Age,}; -         //} +     } -  +     class Program A     { at         Static voidMain (string[] args) -         { -Person P = (person) -;//Call Explicit -             //person p =;//Call Implicit -         } -}

Note: Both are available at the same time, otherwise 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

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.