Detailed Explanation of C Class Declaration

  • 2021-11-29 08:16:04
  • OfStack

Class is declared using the keyword class, as shown in the following example:


 Access modifier  class  Class name  
 { 
 // Class members: 
 // Methods, properties, fields, events, delegates 
 // and nested classes go here. 
 }

1 class should include:

Class name Member Characteristic

A class can contain declarations of the following members:

Constructor Destructor Constant Field Method Attribute Indexer Operator Events Delegate Class Interface Structure

Example:

The following example shows how to declare the fields, constructors, and methods of a class. The example also shows how to instantiate the object and how to print the instance data. In this example, two classes are declared, one is the Child class, which contains two private fields (name and age) and two public methods. The second class, StringTest, is used to contain Main.


class Child
 {
 private int age;
 private string name;
 // Default constructor:
 public Child()
 {
 name = "Lee";
 }
 // Constructor:
 public Child(string name, int age)
 {
 this.name = name;
 this.age = age;
 }
 // Printing method:
 public void PrintChild()
 {
 Console.WriteLine("{0}, {1} years old.", name, age);
 }
 }
 class StringTest
 {
 static void Main()
 {
 // Create objects by using the new operator:
 Child child1 = new Child("Craig", 11);
 Child child2 = new Child("Sally", 10);
 // Create an object using the default constructor:
 Child child3 = new Child();
 // Display results:
 Console.Write("Child #1: ");
 child1.PrintChild();
 Console.Write("Child #2: ");
 child2.PrintChild();
 Console.Write("Child #3: ");
 child3.PrintChild();
 }
 }
 /* Output:
 Child #1: Craig, 11 years old.
 Child #2: Sally, 10 years old.
 Child #3: N/A, 0 years old.
 */

Note: In the above example, the private fields (name and age) can only be accessed through the public methods of the Child class. For example, you cannot print the name of Child with the following statement in the Main method:

Console.Write(child1.name);   // Error 

Private members of this class can only be accessed from Main if Child is a member of Main.

Types are declared in the option class and default to private without access modifiers, so the data members in this example will be private if the keyword is removed.

Finally, note that, by default, the age field is initialized to zero for objects created using the default constructor (child3).

Remarks:

Class is singly inherited in c #. That is, a class can only inherit one base class from. However, one class can implement more than one (one or more) interface. The following table gives one example of class inheritance and interface implementation:

Inheritance 示例
CODE_TAG_REPLACE_MARK_1
Single CODE_TAG_REPLACE_MARK_2
无,实现两个接口 CODE_TAG_REPLACE_MARK_3
单1,实现1个接口 CODE_TAG_REPLACE_MARK_4


Related articles: