[c# tutorial] C# class (Class)

黄舟
Release: 2016-12-26 14:41:36
Original
1181 people have browsed it

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 
    }
}
Copy after login

Note:

The access specifier specifies 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 members is private.

Data type specifies the type of the variable, 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();
        }
    }
}
Copy after login

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

Box1 的体积: 210
Box2 的体积: 1560
Copy after login
Copy after login

Member functions And a member function of a wrapper

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();
        }
    }
}
Copy after login

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

Box1 的体积: 210
Box2 的体积: 1560
Copy after login
Copy after login

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();
      }
   }
}
Copy after login

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

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

Default constructor There are no parameters. But if you need a constructor with parameters that can have parameters, this type of constructor is called a 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();
      }
   }
}
Copy after login

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

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

Destructor in C#

The destructor of a class is a special member function of the class, which 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());           
      }
   }
}
Copy after login

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

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

C# class Static members

We can use the static keyword to 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.

关键字 static 意味着类中只有一个该成员的实例。静态变量用于定义常量,因为它们的值可以通过直接调用类而不需要创建类的实例来获取。静态变量可在成员函数或类的定义外部进行初始化。您也可以在类的定义内部初始化静态变量。

下面的实例演示了静态变量的用法:

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();
        }
    }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

s1 的变量 num: 6
s2 的变量 num: 6
Copy after login

您也可以把一个成员函数声明为 static。这样的函数只能访问静态变量。静态函数在对象被创建之前就已经存在。下面的实例演示了静态函数的用法:

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();
        }
    }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

变量 num: 3
Copy after login

 以上就是【c#教程】C# 类(Class)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
c#
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template