Different meanings of the same name -- function overloading and constructor

Source: Internet
Author: User

As we all know, layer-3 D is mainly used to process data. In general, we use sqlhelper to process input parameters of layer-D. The specific processing is to pass in or not pass in a parameter, returns a bool value or a dataset. Therefore, if we write it one by one, this is the case: first, a function with the return value of the parameter bool, write a function without the return value of the parameter being bool. There is also a function without the return value of the parameter being datatable, and finally a function with the return value of the parameter being datatable, if different names are set for these four parameters, it is very troublesome to consider the function that needs to be called when calling and Processing Layer D, here we need to use function overloading:

Overload:

Function overload:In the same scope, multiple functions with the same functions and different definitions of parameter lists are implemented, this is a special function that uniquely identifies and distinguishes functions through the function parameter list.

Note:

L within the same scope.

L different parameter lists mean that the parameter type, number, and order are at least different.

L function overloading cannot be described by the function return type.

L function Overloading is not required as long as functions are similar or identical. If the information provided by different function names makes the program easier to understand, then using overload functions is no good. For example: Success, →, fail, fail

Heavy Load Resolution:The matching algorithm is used to determine which function of the same name matches the parameter based on the real parameters in the function. The sequence of matching detection is irrelevant to the sequence of function declaration.

To explicitly determine which overload function to call, the compiler must make a resolution for the overload. When the compiler executes the overload resolution, it searches for the "best match" function based on a parameter within the same time period.

The search process ends when a matching function is found based on a specific parameter.

 

Overload resolution rules:To call a function of multiple functions with the same name, each parameter compiler must execute five matching procedures in sequence. No matter what kind of matching process, as long as a match is found, it will stop searching for the parameter and start to do similar work on the next parameter.

Five matching processes:

Full match, including adding the qualifier const and array to pointer conversion.

Upgrade: char-> int, usigned char-> int, signed Char-> int, Enum-> int, short-> int, usigned short-> int, wchar-> int, bool-> int, float-> double.

Standard conversion: Integer Conversion, floating point conversion, floating point Integer Conversion, pointer conversion, pointer member conversion, and base class conversion.

User-Defined conversion: constructor and operator conversion function.

Ellipsis conversion sequence: It is composed of all the functions of the form parameters. It can match any real parameter.

 

Next, let's reload sqlhelper in the news publishing system.

Sqlhelper Abstraction:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. data. sqlclient; using system. data; using system. configuration; using system. data. sqltypes; namespace Dal {public class sqlhelper {private sqlconnection conn = NULL; private sqlcommand cmd = NULL; private sqldatareader SDR = NULL; /// <summary> /// set the database connection parameters /// </Summary> Public sqlhelper () {string connstr = configurationmanager. connectionstrings ["connstr"]. connectionstring; Conn = new sqlconnection (connstr );} /// <summary> /// open the database /// </Summary> /// <returns> </returns> private sqlconnection getconn () {If (Conn. state = connectionstate. closed) {Conn. open ();} return conn ;} /// <summary> /// execute the SQL statement or stored procedure without parameters. /// </Summary> /// <Param name = "plain text"> Add/delete modify an SQL statement or stored procedure </param> /// <Param name = "CT"> command type </param> /// <returns> </returns> Public int executenonquery (string plain text, commandtype CT) {int res; try {sqlcommand cmd = new sqlcommand (plain text, getconn (); cmd. commandtype = CT; Res = cmd. executenonquery ();} catch (exception ex) {Throw ex;} return res ;} /// <summary> /// execute the SQL statement or stored procedure with parameters. /// </Summary> /// <Param name = "plain text"> add, delete, and modify SQL statement or stored procedure </param> /// <Param name = "paras"> </param> /// <Param name = "CT"> command type </Param >/// <returns> </returns> Public int executenonquery (string plain text, sqlparameter [] paras, commandtype CT) {int res; try {using (cmd = new sqlcommand (plain text, getconn () {cmd. commandtype = CT; cmd. parameters. addrange (paras);} res = cmd. executenonquery ();} catch (exception ex) {Throw ex;} return res ;} /// <summary> /// input an SQL statement or stored procedure without parameters /// </Summary> /// <Param name = "plain text"> SQL statement or stored Procedure </param> /// <Param name = "CT"> command type </param> /// <returns> </returns> Public datatable executequery (string plain text, commandtype CT) {datatable dt = new datatable (); sqlcommand cmd = new sqlcommand (plain text, getconn (); cmd. commandtype = CT; using (SDR = cmd. executereader (commandbehavior. closeconnection) {DT. load (SDR) ;}return DT ;} /// <summary> /// input an SQL statement or stored procedure with parameters /// </Summary> /// <Param name = "plain text"> SQL statement or stored procedure </param> /// <Param name = "paras"> parameter array </param> /// <Param name = "CT"> command type </param>/ // <returns> </returns> Public datatable executequery (string plain text, sqlparameter [] paras, commandtype CT) {datatable dt = new datatable (); cmd = new sqlcommand (cmdtext, getconn (); cmd. commandtype = CT; cmd. parameters. addrange (paras); Using (SDR = cmd. executereader (commandbehavior. closeconnection) {DT. load (SDR) ;}return DT ;}}}

When used outside, there is a special function overload, that is, the constructor.

Constructor

Constructor is a special method used to initialize an object when creating an object, that is, assigning an initial value to the object member variable, the new operator is used together with the new operator. In the statement for creating an object, a special class can have multiple constructors to distinguish them (constructors) based on the number of parameters or different parameter types..

1. The name of the constructor must be exactly the same as that of the class.

2. the constructor function is mainly used to define the initialization status when class objects are created. It does not return values and cannot be modified using void. This ensures that it does not have to return anything automatically, and there is no choice at all. Other methods return values, even void. Although the method body does not automatically return anything, it can still let it return something that may be insecure.

3. constructor cannot be called directly. It is automatically called only when the new operator is used to create an object. The general method is called when the program executes it.

4. when defining a class, the constructor of the class is usually displayed, and the initialization work specified in the function can also be omitted. However, the Java compiler provides a default constructor. this default constructor does not contain parameters. The general method does not have this feature.

5. If a class only defines a private constructor, its object cannot be created using the new keyword. If a class does not define any constructor, C # The Compiler automatically generates a default no-argument constructor for it.

In the niugu news publishing system, the question is that when we add news in the News list, the news ID is automatically generated, that is, in our new class, you do not need to input the ID parameter, but you must know the ID when modifying the news list. That is to say, You need to input a new class containing the ID, the constructor does this when I am not touched: the new class contains the ID parameter, which is assigned to him randomly (because it cannot be blank ), this parameter is not used in layer-D applications. Of course, the biggest disadvantage here is that more parameters are passed in, making the code cumbersome and prone to errors. The following code uses the constructor:

Three constructors are defined here:

 public News()        { }        public News(string title, string content, string caid)        {            this.title = title;            this.content = content;            this.caid = caid;        }        public News(string id,string title, string content, string caid)        {            this.id = id;            this.title = title;            this.content = content;            this.caid = caid;        }

In this way, similar to function overloading, you do not need to consider whether Id needs to be passed in during the call, and do not feel awkward when writing code.

I have heard of function overloading before, And I am occasionally engaged in writing code. I have never had a deep understanding of it. I found that I am still confused and found that, in fact, there are a lot of things you don't understand, and you think of that sentence again. The future is bright, and the road is bumpy. Just endure it !!!

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.