C # core basics-class (2 ),
C # core Foundation-class declaration
Class is the use of keywordsclassDeclaration, as shown in the following example:
Access modifier class name {// class member: // Methods, properties, fields, events, delegates // and nested classes go here .}
A class should include:
- Class Name
- Member
- Features
A class can contain the declaration of the following members:
- Constructor
- Destructor
- Constant
- Field
- Method
- Attribute
- Indexer
- Operator
- Event
- Delegate
- Class
- Interface
- Structure
Example:
The following example describes how to declare fields, constructors, and methods of a class. This example also describes how to instantiate an object and how to print instance data. In this example, two classes are declared, one isChildClass, which contains two private fields (nameAndage) And two public methods. Second categoryStringTestUsed to includeMain.
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 preceding example, the private field (nameAndage) OnlyChildClass. For exampleMainUse the following statement to print the Child Name:
Console.Write(child1.name); // Error
Only whenChildYesMainFromMainAccess the Private Members of this class.
The type declaration is in the option class. The default value isprivateTherefore, the data member in this example willprivateIf the keyword is removed.
Note that, by default (child3). The age field is initialized to zero.
Note:
Classes are individually inherited in c. That is to say, the class can only beInheritanceA base class. However, a class can implement more than one(One or more)Interface. The following table provides some examples of class inheritance and interface implementation:
| Inheritance |
Example |
| None |
class ClassA { } |
| Single |
class DerivedClass: BaseClass { } |
| None. Two interfaces are implemented. |
class ImplClass: IFace1, IFace2 { } |
| Single, implement an Interface |
class ImplDerivedClass: BaseClass, IFace1 { } |