search
C# structures and classesFeb 08, 2017 pm 02:39 PM

Classes and structures are the two basic constructs of the same type system in the .NET Framework. Both are essentially data structures that encapsulate a set of data and behaviors as a logical unit. Data and behavior are "members" of the class or structure, and they contain their own methods, properties, events, etc.

Structure

Structure is the most common mechanism used by C# programmers to define their own value types. Structure is more powerful than enumeration as it provides methods, fields, operators and access control etc.

Structures are very similar to classes, and both represent data structures that can contain data members and function members. However, unlike classes, structs are a value type and do not require heap allocation. Variables of structure type directly contain the data of the structure, while variables of class type contain only a reference to the corresponding data (the referenced data is called an "object").

Structures are particularly useful for small data structures with value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all typical examples of structures. The key thing about these data structures is that they have only a small number of data members, do not require the use of inheritance or reference identifiers, and they are easier to use (when assigning, you copy the value directly instead of copying its reference).

# The statement of the structure is implemented by keyword structs. Structure body

      };

                      The structure declaration contains a set of optional attributes, followed by a set of optional struct modifiers, followed by the keyword struct and an identifier used to name the structure , followed by an optional structure interface specification, and finally a structure body, followed by a semicolon if needed.

The structure declaration can contain a structure modifier as needed: new, public, protected, internal, private

## The use of structures

It is a mistake to define a default (no-argument) constructor for a structure, and it is a mistake to re-initialize instance fields in the structure. Initializing structure members can be done in two ways: one is to use a parameterized constructor, and the other is to access the members separately after declaring the structure. Any private members or members that are otherwise made inaccessible can only be initialized in the constructor.

If you use the new operator to create a structure object, the structure object will be created and the appropriate constructor will be called. Unlike classes, structures can be instantiated without using the new operator. In this case there is no constructor call, thus improving allocation efficiency. However, the fields will remain unassigned and the object will not be available until all fields are initialized.

When a structure contains a reference type as a member, the default constructor that calls that member must be explicitly called, otherwise the member will remain unassigned and the structure will be unavailable.

Example question, create a structure and analyze the use of the structure


Class

Class is a data structure that can encapsulate data members (constants and fields), function members (methods, properties, events, indexers, operators, instance constructors, static constructors and destructors) and other classes (nested types). Classes are templates for creating objects. All types in C# are classes, and all statements must be located within the class. There are no statements outside the class. Therefore, classes are the core and basic building blocks of the C# language. Class types support inheritance, a mechanism that enables derived classes to extend and specialize a base class.

The base class specified in the class declaration can be a constructed class type. A base class itself cannot be a type parameter, but it can contain type parameters in its scope.

In the OOP method, a class is a highly abstract and generalized representation of the real world, while an object is an instance of a class. The object must have the common characteristics and behavioral rules of its class. Of course, an object also Can have characteristics and behavioral rules not specified by its category. This is the same as real life. Such simulation and abstraction are more in line with people's thinking habits. This is why the OOP method has strong vitality and can be welcomed by more and more software workers and supported by many computer developers. A basic reason.

## In short, from the perspective of a programmer, a class is a data model and several program processes, which are encapsulated to form a whole. It is the use of information technology to analyze reality. A simulation and abstraction of the world. An object is an instance of a class. From a programming language perspective, an object can be understood as the result of a class assignment. An object is a component that makes up a program in the OOP method.

The declaration of a class in C# is instantiated through the class keyword. The format is:

Modifier class class name: base class or interface

{

Class body

}

Among them, "modifier" and ": base class or interface" are optional. The modifier of a class can be one of the following or a combination thereof (the same modifier is not allowed to appear multiple times in the class declaration ()).

(1)new: Only allowed to be used when declaring a nested class, indicating that the class hides members inherited from the base class and with the same name as the base class

(2 )public: Indicates that access to the class is not restricted

(3)internal: Only the class in which it belongs can access

(4) Private: Only applications or libraries in .NET can access it Access

(5)Abstract: Abstract class, creation of instances of the class is not allowed

(6)Sealed: Sealed class, inheritance is not allowed


Class inheritance statement: C# language only supports single inheritance

(1), constructor and destructor

C# provides a better mechanism to enhance program security sex. The C# compiler has a strict type safety check function, which can find almost all syntax problems in the program. However, just because the program passes the compilation check does not mean that the error no longer exists.

The C# language fully considers the occurrence of program errors and solves them well, that is, placing the object initialization work in the constructor and the cleanup work in the destructor. When an object is created, the constructor is executed automatically. When the object dies, the destructor is executed automatically.


The name of the constructor cannot be chosen casually. It must be recognized by the compiler before it can be automatically executed. Its naming method is simple and reasonable: let the constructor have the same name as the class. In addition to the name, another special feature of the constructor is that it has no return value type, which is different from the function whose return value type is void.


The destructor is a method member that implements the destruction of an instance of a class. The destructor cannot have parameters, cannot have any modifiers and cannot be called. The purpose of the destructor and the constructor is different, so the destructor is prefixed with "~" to show the difference.

Although the constructor and destructor are formally simpler functions in a class. But their use is by no means as simple as it seems, so using constructors and destructors flexibly and correctly can help users better understand the CLR's memory management mechanism and better manage resources in the system.


(2), Classes and Objects

A class is a collection of objects with the same attributes and services. It provides a unified abstract description for all objects belonging to this class, which includes two main parts: properties and services. In object-oriented programming languages, a class is an independent program unit, which has a class name. The class name includes two main parts: attribute description and service description.


An object is an entity used to describe objective things in the system and is a basic unit that constitutes the system. An object consists of a set of properties and a set of services that operate on the set of properties. From a more abstract perspective, an object is an abstraction of something in the problem domain or implementation domain, reflecting the information that needs to be saved and the role that the thing plays in the system. It is a set of attributes and the right to perform operations on these attributes. A wrapper for a set of services that operates. The objective world is composed of objects and the connections between objects.

The relationship between a class and an object is like the relationship between a mold and a casting. The result of instantiation of a class is an object. The abstraction of a type of object is a class. A class describes a group of objects with the same characteristics (properties) and the same behavior (methods).

For more articles related to C# structures and classes, please pay attention to the PHP Chinese website!

Statement
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
How to use char array in C languageHow to use char array in C languageApr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

What is the role of char in C stringsWhat is the role of char in C stringsApr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to use various symbols in C languageHow to use various symbols in C languageApr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

How to handle special characters in C languageHow to handle special characters in C languageApr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between multithreading and asynchronous c#The difference between multithreading and asynchronous c#Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

How to convert char in C languageHow to convert char in C languageApr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the function of C language sum?What is the function of C language sum?Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

The difference between char and wchar_t in C languageThe difference between char and wchar_t in C languageApr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),