Preface
We have said that the constructor initializes the class. We hope that the new kitten has a name called "Mimi". When it is called, it can say "my name is Mimi ", the constructor is required now. The following Code does not contain any green code, but the question is? If we didn't give the kitten a good name in advance, we wouldn't be able to create an instance. This is a normal phenomenon. Some parents just gave birth to a child, it would be very normal that they didn't get a good name, the following code does not contain green code. If you write Cat cat = new Cat (), the system reports the error "Cat method does not use any overload of 0 Parameters, the reason is that you must give a name to the kitten. If you do not need a name, you can use the method to reload it.
Method Overloading
Multiple methods with the same name can be created, but different parameter types are required for these methods.
During method overloading, the two methods must have the same name, but the parameter type or number must be different.
What are the benefits of method overloading?
The advantage of method Overloading is that it adds features without changing the original method.
Instance
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace _ 7_ConstructedFunction
{
Class Program
{
Static void Main (string [] args)
{
Cat cat = new Cat ("Mimi ");
Console. WriteLine (cat. Shout ());
// A kitten can be generated without a name
Cat cat2 = new Cat ();
Console. WriteLine (cat2.Shout ());
Console. ReadKey ();
}
}
Class Cat
{
Private string _ name = "";
// Reload the constructor by adding this green code
Public Cat ()
{
This. _ name = "anonymous ";
}
Public Cat (string name)
{
This. _ name = name;
}
Public string Shout ()
{
Return "my name is" + _ name;
}
}
}
Running Effect
Thoughts
In the above example, some kittens use constructor with the string parameter after their names are ready. If some kittens do not have a name, they use constructor without parameters. This achieves the purpose of extension.
If we need to clarify the Cat's surname and name, we can reload a constructor public Cat (string strFirstName, string strLastName)