The structure and class of C # Supplements

Source: Internet
Author: User

Classes and structs are two basic constructs of the same type of system in the. NET framework. Both essentially belong to the data structure, encapsulating this group as a whole as a logical unit of information and behavior. Data and behavior are "members" of the class or struct, and they contain their own methods, properties, events, and so on.

structure

Structs are the most common mechanism that C # programmers use to define their own value types. Structs are more powerful than enumerations because they provide methods, fields, operations, and access control.

Structs are similar to classes in that they represent data structures that can contain data members and function members. However, unlike classes, structs are a type of value and do not require heap allocation. A variable of a struct type directly contains the data for that structure, and a variable of class type contains only a reference to the corresponding data (the referenced data is called an "object").

Structs are especially useful for small data structures that have value semantics. A complex number, a point in a coordinate system, or a key-value pair in a dictionary are typical examples of structs. The key to these data structures is that they are only small numbers of data members, do not require inheritance or reference identities, and they are more convenient to use (copying values directly instead of copying references).

The declaration of a struct is implemented by a keyword struct, declared in the form:

modifier struct struct name

{

Structure body

};

A struct declaration consists of an optional set of attributes, followed by a set of optional structural modifiers, with the keyword struct and an identifier for the naming structure, followed by an optional struct interface specification, followed by a struct body, followed by a semicolon, as needed.

A struct declaration can include a struct modifier as needed: new,public,protected,internal,private

use of Structures

Defining a default (parameterless) constructor for a struct is an error, and it is also wrong to initialize the instance field in the structure weight. Initialization struct members can be done in two forms: one is to use parameterized constructors, and the other is to access the members separately after the structure is declared. For any private member or otherwise set to a member that is not accessible, it can only be initialized in the constructor.

If you create a struct object using the new operator, the structure object is created and the appropriate constructor is called. Unlike classes, structs can be instantiated without the use of the new operator. In this case there is no call to the constructor, so the allocation efficiency can be increased. However, before all fields are initialized, the field remains unassigned and the object is not available.

When a struct contains a reference type as a member, the default constructor that invokes the member must be explicitly called, otherwise the member remains unassigned and the struct is not available.

example, create a structure, analyze the use of the structure

<span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace text{    struct sum//defines a struct    {public        int Sum (int a, int b)//struct contains the method        {            return a + b;        }    }    Class program    {        static void Main (string[] args)        {            int p = ten;            int q = ten;            Sum t = new sum ();//create struct object T            Console.Write ("{0}+{1}=", p,q);            Console.Write (T.sum (P,Q));//Call the method in the structure            console.readline ();}}    </span>

The result of the output is: 10+10=20

class

A class is a structure that encapsulates data members (constants and fields), function members (methods, properties, events, indexers, operators, instance constructors, static constructors, and destructors), and other classes (nested types). The class is the template that creates the object. All types of C # are classes, all statements must be within the class, and there are no statements outside the class. Therefore, classes are the core and basic constituent modules of the C # language. Class types support inheritance, which is a mechanism that allows derived classes to extend and specialize base classes.

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

In the Oop method, the class is a kind of high abstraction and generalization to the real world, and the object is an instance of the class, the object must have the common characteristic and the behavior rule of its genus, and of course an object can have the characteristic and the rule of behavior that its genus has not stipulated. This is the same as the real life, such simulation and abstraction in line with the people's thinking habits, this is the OOP method has a strong vitality, can get more and more software workers welcome and many computer developers to support a basic reason.

In short, from the perspective of the program designer, the class is a data schema and a number of procedural processes, encapsulated by a whole, is the use of information technology to the real world of a simulation and abstraction. An object is an instance of a class that, from a programming language, can be understood as the result of a class assignment. Objects are a component of a program in an OOP method.

The declaration of a class in C # is through the Class keyword instance, in the following format:

Modifier Class class Name: base class or interface

{

Class Body

}

where "modifier", ": base class or interface" is optional. The modifiers of a class can be one of the following or a combination of them (the same modifier is not allowed to appear more than once in the Declaration () of the Class).

(1) NEW: only allowed when nested class declarations are used, indicating that classes are hidden from the base class, and that members with the same name in the base class

(2) Public: Indicates that access to this class is not restricted

(3) Internal: Only the class in which it is located can access

(4) Private: only right. NET to access the application or library in

(5) Abstract: An abstraction class that does not allow an instance of a class to be established

(6) Sealed: Sealed class, not allowed to be inherited

Use the new keyword to create an instance of the class:

<span style= "FONT-SIZE:18PX;" >    class A    {    }    class B    {        void M ()        {            A A = new A ();        }    } </span>

Class inheritance declaration: Only single inheritance is supported in the C # language

<span style= "FONT-SIZE:18PX;" >    class A    {    }    class b:a    {    }</span>

Constructors and Destructors

C # provides a better mechanism to enhance the security of your program. The C # compiler has a strict type safety check function, which can find almost all the syntax problems in the program. However, the program passes the compile check and does not indicate that the error no longer exists.

The C # language fully considers the occurrence of the program error and solves it well, that is, the initialization of the object is placed in the constructor, and the cleanup work is placed in the destructor. When an object is created, the constructor is automatically executed. The destructor executes automatically when the object dies.

The name of the constructor cannot be random, and it must be recognized by the compiler to be executed automatically. Its naming method is simple and reasonable: make the constructor function the same as the class name. In addition to the name, another special function of the constructor is that there is no return value type, which is different from a function that returns a value of type void.

A destructor is a method member that implements destroying an instance of a class. Destructors cannot have parameters, cannot have any modifiers, and cannot be called. The destructor is different from the purpose of the constructor, and the prefix "~" is added before the destructor to show the difference.

Constructors and destructors are simple forms of functions in a class. But their use is not as simple as it seems, so using constructors and destructors flexibly and correctly can help users better understand the CLR's memory management mechanisms and better manage the resources in the system.

Classes and Objects

A class is a collection of a set of objects that have the same properties and services. It provides a unified, abstract description of all objects that belong to the class, including two main parts of properties and services. In an object-oriented programming language, a class is a separate program unit that has a class name, which includes a description of the property and two main parts of the service description.

An entity used to describe objective things in a system is a basic unit of a system. An object consists of a set of properties and a set of services that operate on that set of properties. From a more abstract point of view, an object is an abstraction of a problem domain or something in the implementation domain that reflects the information and the role that the thing needs to be saved in the system, a set of attributes and a package of services that have permission to manipulate these properties. The objective world is made up of the connections between objects and objects.

The relationship between classes and objects is like the relationship between a mold and a casting, and the result of the instantiation of the class is the object. And the abstraction of a class of objects is classes. Class describes a set of objects that have the same attributes (attributes) and the same behavior (methods).

example, create Class A and call the method sum of Class A in another class

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace text{class    a//created classes    {public        int Sum (int i, int j)//method encapsulated by class        {            return i + J;        }    }    Class    Program {        static void Main (string[] args)        {            A A = new A ();//object of Class A created            int p = ten;            int q = ten;            Console.WriteLine (A.sum (P,Q));//Call the Sum method of Class A            console.readline ();}}    

The result of the output is: 20


        

The structure and class of C # Supplements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.