Heavy-duty operators

Source: Internet
Author: User

Overload operators are used in actual work. However, if some custom types use a few lines of code to reload some common operators (for example, + -*/), this makes programming easy. The overload operator is to tell the compiler +-*/and other operators what operations are performed on the custom type. Pay attention to the following points in the code.

I. Do not change the meaning of the operator as much as possible

2. All Operator Overloading must be declared as public and static.

3. Unlike the extension method, the overloaded method must be within the reloaded type and use the key Operator

The two strings in C # are actually connected to the two strings. If there are two employeedetail types, a set of employeecollection is obtained, for example:

Employeedetail A, B;

....

Employeecollection collection = A + B;

When the compiler encounters the above code, it will automatically call the static method labeled operator + in the employeedetail class, and pass the two operands A and B as parameters to the corresponding method, this method requires a method value to be assigned to collection. Assume that the employeedetail class has three attributes: firstname, middlename, and lastname, And the tostring method is rewritten to return a string that connects the three names, the Code is as follows:

  [Serializable]    public class EmployeeDetail    {        public string FirstName { get; set; }        public string MiddleName { get; set; }        public string LastName { set;get; }        public override string ToString()        {            return string.Format("{0}{1}{2}{3}{4}", FirstName, string.IsNullOrWhiteSpace(MiddleName) ? null : "."                , MiddleName                , string.IsNullOrWhiteSpace(LastName) ? null : ".",                LastName).Trim();        }    }

 

The following code provides support for the "+" Operator for operator overloading:

 public static EmployeeCollection operator +(EmployeeDetail a, EmployeeDetail b)        {            return new EmployeeCollection() { a, b };        }

OK. After adding this method to the employeedetail class, we can write code like the one below:

Employeecollection collection = new employeedetail () {firstname = "Jackson", lastname = "Bruce"} + new employeedetail () {firstname = "Michael", lastname = "Jackson "};

However, this is not perfect. If A, B, and C are all employeedetail types, the following code will throw a compilation error:

Employeecollection collection = A + B + C;

Why does the compilation fail? We all know that expressions except the value assignment operator are executed from left to right, and a + B returns the employeecollection type. The employeecollection type does not overload the "+" operator, and the compiler does not know what operations to perform, therefore, we also have the following two methods:

        public static EmployeeCollection operator +(EmployeeCollection collection, EmployeeDetail a)        {            collection.Add(a);            return collection;        }        public static EmployeeCollection operator +(EmployeeDetail a, EmployeeCollection collection)        {            return collection + a;        }

 

 

This seems to be perfect, but we can do better, for example, to set the string "Jackson. bruce "is directly implicitly converted to the employeedetail type, that is, Jackson. bruce "a string in this format is directly assigned to an object of the employeedetail type, for example, employeedetail Employee =" Jackson. bruce ", You need to overload the implicit type conversion operator. The Code is as follows:

/// <Summary> /// implicit type conversion /// </Summary> /// <Param name = "name"> </param> /// <returns> </returns> Public Static Implicit operator employeedetail (string name) {

/// In fact, you can write a regular expression here to check whether the name string format is valid. If it is invalid, an exception is thrown.
/// String [] arr; return string. isnullorwhitespace (name )? Null: New employeedetail () {firstname = (ARR = Name. Trim (). Split ('.') [0], lastname = arr. length> 1? Arr [arr. length> 2? 2: 1]: NULL, middlename = arr. length> 2? Arr [1]: NULL};} public static employeecollection operator + (employeedetail A, string B) {return New employeecollection () {a, B };}

 

 

You can't wait to try it here. OK, write a console program to test it:

        static void Main(string[] args)        {            EmployeeDetail employee = "Jackson.Bruce";            Console.WriteLine("FirstName={0},MiddleNam={1},LastName={2}", employee.FirstName, employee.MiddleName, employee.LastName);            Console.WriteLine("toString={0}", employee);            Console.WriteLine();            EmployeeCollection collection = "Michael.Jackson" + employee;            collection += "Bruce.Lee";            foreach (var e in collection)            {                Console.WriteLine(e);            }            Console.WriteLine();            collection -= employee;            foreach (var e in collection)            {                Console.WriteLine(e);            }            Console.WriteLine("===end===");            Console.Read();        }

 

 

Running result

 

 

All the Code, including the reloads of other operators, will not be introduced here. Please try again:

 

Using system; using system. collections. generic; using system. LINQ; using system. text; namespace overload operator {[serializable] public class employeedetail {Public String firstname {Get; set;} Public String middlename {Get; set;} Public String lastname {set; get ;} public static employeecollection operator + (employeedetail A, employeedetail B) {return New employeecollection () {a, B};} public static EMPL Oyeecollection operator + (employeecollection collection, employeedetail A) {collection. add (a); Return collection;} public static employeecollection operator + (employeedetail A, employeecollection collection) {return collection + ;} /// <summary> /// implicit type conversion /// </Summary> /// <Param name = "name"> </param> /// <returns> </returns> Public Static Implicit operator employeedetail (string name) {strin G [] arr; return string. isnullorwhitespace (name )? Null: New employeedetail () {firstname = (ARR = Name. Trim (). Split ('.') [0], lastname = arr. length> 1? Arr [arr. length> 2? 2: 1]: NULL, middlename = arr. length> 2? Arr [1]: NULL};} public static employeecollection operator + (employeedetail A, string B) {return New employeecollection () {a, B};} public override string tostring () {return string. format ("{0} {1} {2} {3} {4}", firstname, String. isnullorwhitespace (middlename )? Null: ".", middlename, String. isnullorwhitespace (lastname )? Null :". ", lastname ). trim () ;}} public class employeecollection: List <employeedetail> {public static employeecollection operator + (employeecollection A, string B) {. add (B); return a;} public static employeecollection operator + (string B, employeecollection A) {return a + B;} public static employeecollection operator-(employeecollection A, employeedetail B) {. remove (B); return a ;}} class program {static void main (string [] ARGs) {employeedetail Employee = "Jackson. bruce "; console. writeline ("firstname = {0}, middlenam = {1}, lastname = {2}", employee. firstname, employee. middlename, employee. lastname); console. writeline ("tostring = {0}", employee); console. writeline (); employeecollection collection = "Michael. jackson "+ employee; Collection + =" Bruce. lee "; foreach (VAR e in Collection) {console. writeline (E);} console. writeline (); Collection-= employee; foreach (VAR e in Collection) {console. writeline (E);} console. writeline ("= END ="); console. read ();}}}

 

 

 

 

 

 

 

 

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.