C # Tutorial C # classes (Class)

Source: Internet
Author: User

C # classes (Class)

When you define a class, you define a blueprint for the data type. This does not actually define any data, but it defines what the name of the class means, that is, what constitutes the object of the class and what operations are performed on the object. An object is an instance of a class. The methods and variables that make up the class become members of the class.

Definition of Class

The definition of a class begins with the keyword class followed by the name of the class. The body of the class, contained within a pair of curly braces. The following is the general form of the class definition:

<access specifier> class  class_name {    //member variables <access specifier> <data    type> Variable1;    <access specifier> <data type> variable2;    ...    <access specifier> <data type> Variablen;    Member Methods    <access specifier> <return type> method1 (parameter_list)     {        //method body     }    <access specifier> <return type> method2 (parameter_list)     {        //method body     }    ...    <access specifier> <return type> methodn (parameter_list)     {        //method body     }}

Please note:

The access identifier <access specifier> Specifies the access rules for the class and its members. If not specified, the default access identifier is used. The default access identifier for a class is internal, and the member's default access identifier is private.

The data type <data type> Specifies the type of the variable, the return type <return type> Specifies the data type returned by the returned method.

If you want to access members of a class, you use the dot (.) operator.

The point operator links the name of the object and the name of the member.

The following example illustrates the concepts discussed so far:

Using System;namespace boxapplication{class Box {public double length;  Length public double breadth;   Width public double height;        Height} class Boxtester {static void Main (string[] args) {Box Box1 = new box ();        Statement Box1, type box box Box2 = new box ();         Declare Box2, type Box double volume = 0.0;            Volume//Box1 Detailed box1.height = 5.0;            Box1.length = 6.0;            Box1.breadth = 7.0;            Box2 detailed box2.height = 10.0;            Box2.length = 12.0;                       Box2.breadth = 13.0;            Box1 Volume volume = box1.height * Box1.length * box1.breadth;            Console.WriteLine ("Volume of Box1: {0}", volume);            Box2 Volume volume = box2.height * Box2.length * box2.breadth;            Console.WriteLine ("Volume of Box2: {0}", volume);        Console.readkey (); }    }}

When the above code is compiled and executed, it produces the following results:

Volume of Box1: Volume of 210box2:1560

member functions and encapsulation

A member function of a class is a function that has its definition or prototype in the class definition, just like any other variable. As a class, it can operate on any object of the class and can access all members of the class of that object.

Member variables are properties of objects (from a design perspective), and they remain private for encapsulation. These variables can only be accessed using public member functions.

Let's use the concepts above to set and get the values of different class members in a class:

Using System;namespace boxapplication{class Box {private double length;  length private double breadth;   width private double height;       Height public void setLength (double len) {length = Len;       } public void Setbreadth (double bre) {breadth = bre;       } public void SetHeight (double hei) {height = hei;       } public double Getvolume () {return length * breadth * height;        }} class Boxtester {static void Main (string[] args) {Box Box1 = new box (); Statement Box1, type box box Box2 = new box (); Declare Box2, type Box double volume;            Volume//Box1 detailed box1.setlength (6.0);            Box1.setbreadth (7.0);            Box1.setheight (5.0);            Box2 detailed box2.setlength (12.0);            Box2.setbreadth (13.0);                   Box2.setheight (10.0); The body of the Box1Product volume = Box1.getvolume ();            Console.WriteLine ("Volume of Box1: {0}", volume);            Box2 Volume volume = Box2.getvolume ();                       Console.WriteLine ("Volume of Box2: {0}", volume);        Console.readkey (); }    }}

When the above code is compiled and executed, it produces the following results:

Volume of Box1: Volume of 210box2:1560

Constructors in C #

The constructor of a class is a special member function of a class that executes when a new object of the class is created.

The name of the constructor is exactly the same as the name of the class, and it does not have any return type.

The following example illustrates the concept of a constructor:

Using System;namespace lineapplication{   class line   {      private double length;   The length of the line is public lines      ()      {         Console.WriteLine ("Object created");      }      public void SetLength (double len)      {         length = len;      }      Public double GetLength ()      {         return length;      }      static void Main (string[] args)      {line line         = new Line ();             Set the line length         line.setlength (6.0);         Console.WriteLine ("Length of line: {0}", Line.getlength ());         Console.readkey ();}}}   

When the above code is compiled and executed, it produces the following results:

Length of the line to which the object has been created: 6

The default constructor does not have any parameters. But if you need a constructor with parameters that can have parameters, this constructor is called a parameterized constructor. This technique can help you to assign an initial value to an object while creating an object, see the following example:

Using System;namespace lineapplication{   class line   {      private double length;   Length of Line      (double len)  //parameterized constructor      {         Console.WriteLine ("object created, length = {0}", Len);         length = len;      }      public void SetLength (double len)      {         length = len;      }      Public double GetLength ()      {         return length;      }      static void Main (string[] args)      {line line         = new Line (10.0);         Console.WriteLine ("Length of line: {0}", Line.getlength ());          Set the line length         line.setlength (6.0);         Console.WriteLine ("Length of line: {0}", Line.getlength ());          Console.readkey ();}}}   

When the above code is compiled and executed, it produces the following results:

The object has been created, length = 10 of the line: 10 length of the line: 6

Destructors in C #

A destructor for a class is a special member function of a class that executes when the object of the class goes out of scope.

The name of the destructor is prefixed with a tilde (~) in front of the name of the class, and it does not return a value or any parameters.

Destructors are used to release resources before ending programs, such as closing files, freeing memory, and so on. Destructors cannot be inherited or overloaded.

The following example illustrates the concept of a destructor:

Using System;namespace lineapplication{   class line   {      private double length;   The length of the line is public lines      ()  //constructor      {         Console.WriteLine ("Object created");      }      ~line ()//destructor      {         Console.WriteLine ("Object deleted");      }      public void SetLength (double len)      {         length = len;      }      Public double GetLength ()      {         return length;      }      static void Main (string[] args)      {line line         = new Line ();         Set the line length         line.setlength (6.0);         Console.WriteLine ("Length of line: {0}", Line.getlength ());}}}   

When the above code is compiled and executed, it produces the following results:

Length of the line to which the object has been created: 6 object deleted

Static members of C # classes

We can use the static keyword to define a class member as static. When we declare a class member to be static, it means that no matter how many classes of objects are created, there will only be one copy of that static member.

The keyword static means that there is only one instance of the member in the class. Static variables are used to define constants, because their values can be obtained by invoking the class directly without creating an instance of the class. A static variable can be initialized outside the definition of a member function or class. You can also initialize static variables inside the definition of a class.

The following example demonstrates the use of static variables:

Using System;namespace staticvarapplication{    class Staticvar    {public       static int num;        public void count ()        {            num++;        }        public int Getnum ()        {            return num;        }    }    Class Statictester    {        static void Main (string[] args)        {            Staticvar s1 = new Staticvar ();            Staticvar s2 = new Staticvar ();            S1.count ();            S1.count ();            S1.count ();            S2.count ();            S2.count ();            S2.count ();                     Console.WriteLine ("S1 variable num: {0}", S1.getnum ());            Console.WriteLine ("S2 variable num: {0}", S2.getnum ());            Console.readkey ();}}}    

When the above code is compiled and executed, it produces the following results:

Variable of s1 variable num:6s2 num:6

You can also declare a member function as static. Such a function can only access static variables. A static function already exists before the object is created. The following example demonstrates the use of a static function:

Using System;namespace staticvarapplication{    class Staticvar    {public       static int num;        public void count ()        {            num++;        }        public static int Getnum ()        {            return num;        }    }    Class Statictester    {        static void Main (string[] args)        {            Staticvar s = new Staticvar ();            S.count ();            S.count ();            S.count ();                               Console.WriteLine ("Variable num: {0}", Staticvar.getnum ());            Console.readkey ();}}}    

When the above code is compiled and executed, it produces the following results:

Variable Num:3

This is the "C # Tutorial" C # classes (Class) content, more relevant content please follow topic.alibabacloud.com (www.php.cn)!


  • Related Article

    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.