Role: helps us initialize the image (assigning values to each property of the image in turn)
Constructors are a special method
1, the constructor does not return a value, even void can not write
2. The constructor name should be the same as the class name
3. Constructors are executed when creating a pair of images
4. Constructors can be overloaded
There is a constructor (hidden) in the default class, and if you create a constructor, whether it is a parameter or no argument, his default parameterless constructor disappears, and if you need to re-write it without a parameter
Students class
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceclasslibrary1{ Public classStudents {//create a pair of images using PublicStudents (stringNameintAgeCharGenderintEnglist,intChinese,intmath) { This. Name =name; This. Age =Age ; This. Gender =gender; This. Englist =englist; This. Chinese =Chinese; This. Math =Math; } PublicStudents (stringNameintAge ) { This. Name =name; This. Age =Age ; } Private string_name; Public stringName {Get{return_name;} Set{_name =value;} } Private int_age; Public intAge {Get{return_age;} Set { if(Value <0|| Value > -) {Value=0; } _age=value; } } Private Char_gender; Public CharGender {Get { if(_gender! ='male'&& _gender! ='female') {_gender='male'; } return_gender; } Set{_gender =value;} } Private int_chinese; Public intChinese {Get{return_chinese;} Set{_chinese =value;} } Private int_math; Public intMath {Get{return_math;} Set{_math =value;} } Private int_english; Public intEnglist {Get{return_english;} Set{_english =value;} } Public voidSayHello () {Console.WriteLine ("My name is {0}, I am {1} sex, I am {2} years old this year", This. Name, This. Gender, This. Age); } Public voidShowscore () {Console.WriteLine ("My name is { 0}, my total score is {1}, my average result is {2}", This. Name, This. Chinese + This. Math + This. Englist, ( This. Chinese + This. Math + This. Englist)/3); } }}
Program Class
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceclasslibrary1{ Public Static classProgram { Public Static voidMain (string[] args) {Students ZS=NewStudents ("Zhang San", +,'male', -, A, -); Zs. SayHello (); Zs. Showscore (); Students ls=NewStudents ("John Doe", -,'female', the, the, +); Ls. SayHello (); Ls. Showscore (); Console.readkey (); } }}
The C # constructor uses