C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# Class



#When you define a class, you define a blueprint of a data type. This doesn't actually define any data, but it defines what the name of the class means, that is, what an object of the class consists of and what operations can be performed on this object. Objects are instances of classes. The methods and variables that make up a class become members of the class.

Definition of class

The definition of a class starts with the keyword class, followed by the name of the class. The body of the class, enclosed within a pair of curly braces. The following is the general form of a 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 for a member is private.

  • Data type <data type> specifies the type of the variable, 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 dot 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;   // 长度
       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 other variables. As a member of a class, it can operate on any object of the class and can access all members of the class of the object.

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

Let us use the above concepts 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 will produce the following results:

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

Constructor in C

#The constructor of a class is a special member function of the 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, it does not have any return type.

The following example illustrates the concept of constructor:

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 will produce the following results:

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

Default The constructor does not have any parameters. But if you need a constructor with parameters, this constructor is called Parameterized Constructor. This technique can help you assign initial values ​​to objects while creating them. Please see the following example for details:

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 will produce the following results:

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

Destructor in C

#The destructor of a class is a special member function of the class that is executed when the object of the class goes out of scope.

The name of the destructor is prefixed with a tilde (~) before the name of the class. It does not return a value and does not take any parameters.

The destructor is used to release resources before ending the program (such as closing files, releasing memory, etc.). Destructors cannot be inherited or overloaded.

The following example illustrates the concept of destructor:

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 will produce the following results:

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

Static members of C# classes

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

Keyword static means there is only one instance of this member in the class. Static variables are used to define constants because their values ​​can be obtained by calling the class directly without creating an instance of the class. Static variables can be initialized outside a member function or class definition. You can also initialize static variables inside the definition of a class.

The following example demonstrates the usage 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 will produce the following results:

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

You can also declare a member function as static. Such functions can only access static variables. Static functions exist before the object is created. The following example demonstrates the usage of 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("变量 num: {0}", StaticVar.getNum());
            Console.ReadKey();
        }
    }
}

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

变量 num: 3

php.cn