C # static class [reprinted]

Source: Internet
Author: User
C # static class

Static classes cannot be instantiated. We directly use their attributes and methods. The biggest feature of static classes is sharing.

Exploration

Public static class statictestclass
{
Public static int n = 0;

Public static void add ()
{
N ++;
}
}

  • The webpage p1.aspx calls statictestclass. Add () and outputs N on the page.
  • The webpage p2.aspx calls statictestclass. Add () and outputs N on the page.

 

  • Visitor V1 accesses p1.aspx from client C1, and the output is 1.
  • Visitor V2 accesses p2.aspx from client C2, and the output is 2.
  • Visitor V1 closes the browser and re-opens access p1.aspx. The output is 3.

As long as statictestclass is not re-compiled, even if p1.aspx and p2.aspx are re-compiled, Every time statictestclass. Add () is called, N will add 1 to the previous one.

Principles

  • All the Members in the static class must be static.

Static Constructor

  • Static classes can have static constructor, but static constructor cannot inherit.
  • Static constructors can be used for static classes or non-static classes.
  • The static constructor has no access modifier and no parameters. It has only one static flag.
  • A static constructor cannot be called directly. A static constructor is automatically executed only once before a class instance is created or any static member is referenced.

 

 

 

  • Class and structure instance comparison
  • Differences between classes and structures
  • How to Select structure or Class

Comparison of classes and structures

Structure example

Public struct person
{
String name;
Int height;
Int weight

Public bool overweight ()
{
// Implement something}
}

Class Example

Public class testtime
{
Int hours;
Int minutes;
Int seconds;

Public void passtime ()
{
// Implementation of behavior
}
}

Call Process

Public class test
{
Public static Ovid main
{
Person myperson = new person // declaration Structure
Testtime mytime = new testtime // Declaration class
}
}

From the above example, we can see that the declaration of the class and the declaration of the structure are very similar, but the difference between struct and class is after the qualifier, and when used, similar methods are used to define new structures and new classes. What are the specific differences between classes and structures?

Differences between classes and structures

Value Type and reference type

Structure

The structure is a value type, and the value type is allocated to the stack. All base types are structure types. For example, int corresponds to system. int32 structure. String corresponds to system. string Structure. You can create more value types by using the structure.

Class

Class is the reference type, and the reference type is allocated on the stack.

The execution efficiency of stacks is higher than the execution efficiency of stacks. However, the stack resources are limited and it is not suitable for processing large logical and complex objects. Therefore, structure processing is a small object treated as a base type, and classes process a business logic.

Because the structure is a value type, you can create a new structure by assigning values between structures. Classes are reference types, and assigning values between classes is just copying references.

Note:

  • Although the structure and class types are different, their base types are all objects, and all types of base types in C # Are objects.
  • Although the new operator is used for structure initialization, the structure object is still allocated on the stack instead of the stack. If the new operator is not used, before all fields are initialized, the field remains unassigned and the object is unavailable.

Inheritance

Structure

It cannot be inherited from another structure or class. Although the structure is not explicitly declared using sealed, the structure is implicit sealed.

Class

Fully scalable. Unless the declared sealed is displayed, the class can inherit other classes and interfaces, and its own can also be inherited.

Note:

  • Although the structure cannot be inherited, the structure can inherit interfaces. methods are the same as class inheritance interfaces.

    Example: structure implementation Interface

    Interface iimage
    {
    Void paint ();
    }
     
    Struct picture: iimage
    {
    Public void paint ()
    {
    // Painting code goes here
    }

    Private int x, y, z;
    // Other struct members
    }

Internal Structure

Structure

  • No default constructor exists, but you can add constructor.
  • No destructor
  • No abstract and sealed (because it cannot be inherited)
  • The protected modifier cannot exist.
  • You do not need to use new for initialization.
  • It is incorrect to initialize the instance field in the structure.

Class

  • Default constructor available
  • Destructor
  • Abstract and sealed can be used.
  • There is a protected Modifier
  • New must be used for initialization.

How to Select structure or Class

After discussing the similarities and differences between structures and classes, we will discuss how to choose a structure or a class:

  • Stack space is limited. For a large number of logical objects, creating classes is better than creating structures.
  • Structure indicates a lightweight object such as vertex, rectangle, and color. For example, if an array containing 1000 vertex objects is declared, additional memory will be allocated to each referenced object. In this case, the structure cost is low.
  • Classes are the best choice for presentation of abstract and multi-level object layers.
  • In most cases, this type is only the best choice for the structure of some data.

----

Answers from users on csdn:

The structure can be seen as a lightweight class, which is better in performance.

Similarities:

  • Structures and classes are pointer-oriented for programs.

Differences:

  • Struct objects always operate on the thread stack, rather than hosting the stack.
  • A struct cannot be inherited (therefore, you do not need to find the vtable when calling the struct method: the virtual function inherits the table)
  • We cannot declare a struct with an empty Constructor (I don't know why we have to design it like this)
  • All variables must be initialized in the constructor of the struct (I don't know why I have to design it like this)
  • The struct field cannot have a default value (the default value is zero in binary), but the "Default Value" can be changed in the constructor"

.....

According to the meaning on msdn, It is very small in practice to use struct. The structure guide:

  • The behavior is the same as the primitive type.
  • Instance size smaller than 16 bytes.
  • It cannot be changed.
  • Value semantics is desirable.

 

In the difference between structure and class in C #, I have already introduced the knowledge of struct. In this article, I will emphasize, supplement, and correct the application.

About Fields

You Cannot initialize a field when declaring it, unless it is marked as const or static.

Constructor

The constructor must have parameters.

The constructor must assign values to all fields.

Description

It is not allowed to explicitly declare a constructor without parameters in the structure. To explicitly declare a constructor, it must have parameters. However, you can use a constructor without parameters or a constructor with parameters when using new instantiation, which indicates that there is an invisible default non-parameter constructor, the difference between structures and classes in C # is incorrect because the structure "has no default constructor.

Do you want to use new?

If you use properties and methods in the structure, you must use new; otherwise, you can use new.

 

 

Nested type

 

A type defined within a class or structure is a nested type. For example:

class Container{    class Nested    {        Nested() { }    }}

No matter whether the external type is a class or a structure, the nested type is private by default, but it can be set to public, protected internal, protected, internal, or private. In the preceding example, nested is not accessible to external types, but can be set to public, as shown below:

class Container{    public class Nested    {        Nested() { }    }}

The nested type (or internal type) can access the include type (or external type ). To access the include type, pass it as a constructor to the nested type. For example:

public class Container{    public class Nested    {        private Container m_parent;        public Nested()        {        }        public Nested(Container parent)        {            m_parent = parent;        }    }}

Nested types can access private members and protected members that contain types (including all inherited Private Members or protected members ).

In the previous declaration, the complete name of the class nested is container. nested. This is the name of the new instance used to create the nested class, as shown below:

Container.Nested nest = new Container.Nested();

 

Static classes cannot be instantiated. We directly use their attributes and methods. The biggest feature of static classes is sharing.

Exploration

Public static class statictestclass
{
Public static int n = 0;

Public static void add ()
{
N ++;
}
}

  • The webpage p1.aspx calls statictestclass. Add () and outputs N on the page.
  • The webpage p2.aspx calls statictestclass. Add () and outputs N on the page.

 

  • Visitor V1 accesses p1.aspx from client C1, and the output is 1.
  • Visitor V2 accesses p2.aspx from client C2, and the output is 2.
  • Visitor V1 closes the browser and re-opens access p1.aspx. The output is 3.

As long as statictestclass is not re-compiled, even if p1.aspx and p2.aspx are re-compiled, Every time statictestclass. Add () is called, N will add 1 to the previous one.

Principles

  • All the Members in the static class must be static.

Static Constructor

  • Static classes can have static constructor, but static constructor cannot inherit.
  • Static constructors can be used for static classes or non-static classes.
  • The static constructor has no access modifier and no parameters. It has only one static flag.
  • A static constructor cannot be called directly. A static constructor is automatically executed only once before a class instance is created or any static member is referenced.

 

 

 

  • Class and structure instance comparison
  • Differences between classes and structures
  • How to Select structure or Class

Comparison of classes and structures

Structure example

Public struct person
{
String name;
Int height;
Int weight

Public bool overweight ()
{
// Implement something}
}

Class Example

Public class testtime
{
Int hours;
Int minutes;
Int seconds;

Public void passtime ()
{
// Implementation of behavior
}
}

Call Process

Public class test
{
Public static Ovid main
{
Person myperson = new person // declaration Structure
Testtime mytime = new testtime // Declaration class
}
}

From the above example, we can see that the declaration of the class and the declaration of the structure are very similar, but the difference between struct and class is after the qualifier, and when used, similar methods are used to define new structures and new classes. What are the specific differences between classes and structures?

Differences between classes and structures

Value Type and reference type

Structure

The structure is a value type, and the value type is allocated to the stack. All base types are structure types. For example, int corresponds to system. int32 structure. String corresponds to system. string Structure. You can create more value types by using the structure.

Class

Class is the reference type, and the reference type is allocated on the stack.

The execution efficiency of stacks is higher than the execution efficiency of stacks. However, the stack resources are limited and it is not suitable for processing large logical and complex objects. Therefore, structure processing is a small object treated as a base type, and classes process a business logic.

Because the structure is a value type, you can create a new structure by assigning values between structures. Classes are reference types, and assigning values between classes is just copying references.

Note:

  • Although the structure and class types are different, their base types are all objects, and all types of base types in C # Are objects.
  • Although the new operator is used for structure initialization, the structure object is still allocated on the stack instead of the stack. If the new operator is not used, before all fields are initialized, the field remains unassigned and the object is unavailable.

Inheritance

Structure

It cannot be inherited from another structure or class. Although the structure is not explicitly declared using sealed, the structure is implicit sealed.

Class

Fully scalable. Unless the declared sealed is displayed, the class can inherit other classes and interfaces, and its own can also be inherited.

Note:

  • Although the structure cannot be inherited, the structure can inherit interfaces. methods are the same as class inheritance interfaces.

    Example: structure implementation Interface

    Interface iimage
    {
    Void paint ();
    }
     
    Struct picture: iimage
    {
    Public void paint ()
    {
    // Painting code goes here
    }

    Private int x, y, z;
    // Other struct members
    }

Internal Structure

Structure

  • No default constructor exists, but you can add constructor.
  • No destructor
  • No abstract and sealed (because it cannot be inherited)
  • The protected modifier cannot exist.
  • You do not need to use new for initialization.
  • It is incorrect to initialize the instance field in the structure.

Class

  • Default constructor available
  • Destructor
  • Abstract and sealed can be used.
  • There is a protected Modifier
  • New must be used for initialization.

How to Select structure or Class

After discussing the similarities and differences between structures and classes, we will discuss how to choose a structure or a class:

  • Stack space is limited. For a large number of logical objects, creating classes is better than creating structures.
  • Structure indicates a lightweight object such as vertex, rectangle, and color. For example, if an array containing 1000 vertex objects is declared, additional memory will be allocated to each referenced object. In this case, the structure cost is low.
  • Classes are the best choice for presentation of abstract and multi-level object layers.
  • In most cases, this type is only the best choice for the structure of some data.

----

Answers from users on csdn:

The structure can be seen as a lightweight class, which is better in performance.

Similarities:

  • Structures and classes are pointer-oriented for programs.

Differences:

  • Struct objects always operate on the thread stack, rather than hosting the stack.
  • A struct cannot be inherited (therefore, you do not need to find the vtable when calling the struct method: the virtual function inherits the table)
  • We cannot declare a struct with an empty Constructor (I don't know why we have to design it like this)
  • All variables must be initialized in the constructor of the struct (I don't know why I have to design it like this)
  • The struct field cannot have a default value (the default value is zero in binary), but the "Default Value" can be changed in the constructor"

.....

According to the meaning on msdn, It is very small in practice to use struct. The structure guide:

  • The behavior is the same as the primitive type.
  • Instance size smaller than 16 bytes.
  • It cannot be changed.
  • Value semantics is desirable.

 

In the difference between structure and class in C #, I have already introduced the knowledge of struct. In this article, I will emphasize, supplement, and correct the application.

About Fields

You Cannot initialize a field when declaring it, unless it is marked as const or static.

Constructor

The constructor must have parameters.

The constructor must assign values to all fields.

Description

It is not allowed to explicitly declare a constructor without parameters in the structure. To explicitly declare a constructor, it must have parameters. However, you can use a constructor without parameters or a constructor with parameters when using new instantiation, which indicates that there is an invisible default non-parameter constructor, the difference between structures and classes in C # is incorrect because the structure "has no default constructor.

Do you want to use new?

If you use properties and methods in the structure, you must use new; otherwise, you can use new.

 

 

Nested type

 

A type defined within a class or structure is a nested type. For example:

class Container{    class Nested    {        Nested() { }    }}

No matter whether the external type is a class or a structure, the nested type is private by default, but it can be set to public, protected internal, protected, internal, or private. In the preceding example, nested is not accessible to external types, but can be set to public, as shown below:

class Container{    public class Nested    {        Nested() { }    }}

The nested type (or internal type) can access the include type (or external type ). To access the include type, pass it as a constructor to the nested type. For example:

public class Container{    public class Nested    {        private Container m_parent;        public Nested()        {        }        public Nested(Container parent)        {            m_parent = parent;        }    }}

Nested types can access private members and protected members that contain types (including all inherited Private Members or protected members ).

In the previous declaration, the complete name of the class nested is container. nested. This is the name of the new instance used to create the nested class, as shown below:

Container.Nested nest = new Container.Nested();

 

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.