C # is different from Java. You can create value types in C #, And all types created in Java are reference types. When using C # development, select the value type or reference type for ourProgramSo we need to understand the use cases of value types and reference types and distinguish them.
1. Reasons for introducing the reference type and Value Type
C # The difference between the value type and the reference type is that C ++ and Java have common problems. In C ++, all parameters and return values are passed through value classes. It is very efficient to pass the value, but it will bring about the problem of partial copying: that is, when a derived class is introduced where the base class is required, then, only the part of the base class will be copied, and all the information in the derived class will be lost. All the parameters and return values in Java are transmitted as references, the advantage of this method is its consistency, but its performance will be affected. So C # To avoid this, you can use the class keyword and struct keyword to create the reference type and value type respectively.
2. Differences between value types and reference types
When using C # To create a class, we can choose to use struct or class keywords to create the value type and reference type respectively. before using the reference type and value type, we should know the difference between the two:
The value type cannot realize polymorphism and is suitable for storing data. The reference type supports polymorphism and is suitable for defining program behavior.
The value type should be small and lightweight, and the reference type is used to form a class hierarchy
3. When to use the value type
In most cases, the type we create belongs to the reference type. If the type you create meets the following conditions, the value type should be used:
- This type is mainly used for data storage.
- This type of public interface is defined by the attribute of the access data member.
- This type will never have a derived class
- This type never requires support for Polymorphism
Section
The value type indicates the type of data stored at the underlying layer. The reference type is used to encapsulate program behavior. This ensures that the data exposed by the class can be securely provided in the form of replication, as well as the memory performance improvement caused by stack-based storage and the use of inline storage, standard object-oriented technology can be used to express the logic of an application. If the usage of the class is not determined, the reference type should be used.