Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Class of Class


May 11, 2021 C#


Table of contents


Class

When you define a class, you define a blueprint for a data type. T his does not actually define any data, but it does define what the name of the class means, that is, what the object of the class consists of and what can be done on that object. A n object is an instance of a class. The methods and variables that make up the class become members of the class.

The definition of the class

The definition of a class starts with the keyword class, followed by the name of the class. T he body of the class, contained in a pair of flower brackets. Here 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, slt;access specifier, specifies access rules for classes and their members. I f not specified, the default access identifier is used. The default access identifier for a class is internal, and the default access identifier for a member is private.
  • The data type, the data type, specifies the type of variable, and the return type, the return type, specifies the type of data returned by the method returned.
  • If you want to access members of a class, you want to use the point (.) operator.
  • The point operator links the name of the object to the name of the member.

The following example illustrates the concepts discussed so far:

using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // 长度
       public double breadth;  // 宽度
       public double height;   // 高度
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // 声明 Box1,类型为 Box
            Box Box2 = new Box();        // 声明 Box2,类型为 Box
            double volume = 0.0;         // 体积

            // Box1 详述
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            // Box2 详述
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;
           
            // Box1 的体积
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Box1 的体积: {0}",  volume);

            // Box2 的体积
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Box2 的体积: {0}", volume);
            Console.ReadKey();
        }
    }
}

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

Box1 的体积: 210
Box2 的体积: 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 member of a class, it can operate on any object of the class and has access to all members of the class of that object.

Member variables are the properties of an object (from a design perspective) and they remain private to implement encapsulation. These variables can only be accessed using public member functions.

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

using System;
namespace BoxApplication
{
    class Box
    {
       private double length;   // 长度
       private double breadth;  // 宽度
       private double 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();        // 声明 Box1,类型为 Box
            Box Box2 = new Box();        // 声明 Box2,类型为 Box
            double volume;              // 体积


            // Box1 详述
            Box1.setLength(6.0);
            Box1.setBreadth(7.0);
            Box1.setHeight(5.0);

            // Box2 详述
            Box2.setLength(12.0);
            Box2.setBreadth(13.0);
            Box2.setHeight(10.0);
       
            // Box1 的体积
            volume = Box1.getVolume();
            Console.WriteLine("Box1 的体积: {0}" ,volume);

            // Box2 的体积
            volume = Box2.getVolume();
            Console.WriteLine("Box2 的体积: {0}", volume);
           
            Console.ReadKey();
        }
    }
}

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

Box1 的体积: 210
Box2 的体积: 1560

The constructor in C#

The constructor of a class is a special member function of a class that is executed 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 constructors:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // 线条的长度
      public Line()
      {
         Console.WriteLine("对象已创建");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();    
         // 设置线条长度
         line.setLength(6.0);
         Console.WriteLine("线条的长度: {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

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

对象已创建
线条的长度: 6

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

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // 线条的长度
      public Line(double len)  // 参数化构造函数
      {
         Console.WriteLine("对象已创建,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("线条的长度: {0}", line.getLength()); 
         // 设置线条长度
         line.setLength(6.0);
         Console.WriteLine("线条的长度: {0}", line.getLength()); 
         Console.ReadKey();
      }
   }
}

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

对象已创建,length = 10
线条的长度: 10
线条的长度: 6

The destructor in C#

A class's destructor is a special member function of a class that executes when the class's objects are out of range.

The name of the destructor is to prefix the name of the class with a wavy (-) shape, which does not return a value and does not have any parameters.

Destructors are used to free 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 destructors:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // 线条的长度
      public Line()  // 构造函数
      {
         Console.WriteLine("对象已创建");
      }
      ~Line() //析构函数
      {
         Console.WriteLine("对象已删除");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();
         // 设置线条长度
         line.setLength(6.0);
         Console.WriteLine("线条的长度: {0}", line.getLength());           
      }
   }
}

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

对象已创建
线条的长度: 6
对象已删除

The static member of the class

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

The keyword static means that there is only one instance of that member in the class. S tatic variables are used to define constants because their values can be obtained by calling the class directly without creating an instance of the class. S tatic variables can be initialized outside the definition of a member function or class. You can also initialize static variables within 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 的变量 num: {0}", s1.getNum());
            Console.WriteLine("s2 的变量 num: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}

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

s1 的变量 num: 6
s2 的变量 num: 6

You can also declare a member function as static. S uch functions can only access static variables. S tatic functions exist before objects are created. The following example demonstrates the use of static functions:

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("变量 num: {0}", StaticVar.getNum());
            Console.ReadKey();
        }
    }
}

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

变量 num: 3