In the previous article, we talked about two types supported by CLR:
Reference-typeAnd
Value-type,This article describes in detail the class ).
Class(Class) is the most basic C # type. A class is a data structure that combines state (field) and Operation (method and other function members) in a unit. The class is a dynamically created class.Instance(Instance) provides a definition, the instance is also calledObject(Object ). Class SupportInheritance(Inheritance) andPolymorphism(Polymorphism), which isDerived class(Derived class) can be used for extension and specializationBase Class(Base class) mechanism. Class instances are created using the new operator, which allocates memory for the new instance, calls the constructor to initialize the instance, and returns a reference to the instance. When an object is no longer used, the memory occupied by the object is automatically withdrawn. In C #, it is neither necessary nor possible to explicitly release the memory allocated to the object.
The class package can contain the following members :(
Static Member(Static member), or
Instance Member(Instance member ). Static members belong to the class, and instance members belong to the class instance)
Member |
Description |
Constant |
Constant value associated with the class |
Field |
Class variables |
Method |
Class executable computing and operations |
Attribute |
Operations associated with the name attribute of a read/write class |
Indexer |
Operations associated with instances that index classes in array Mode |
Event |
Notifications generated by classes |
Operator |
Class supports conversion and expression Operators |
Constructor |
Operations required for initializing an instance or Class |
Destructor |
Operations performed before permanently discarding an instance of the class |
Type |
The nested type declared by the class |
Take the following example:
Public
Sealed
ClassSomeType
{// 1
// Nested class
Private
ClassSomeNestedType {} // 2
// Constant, read-only field, static field
Private
ConstInt32 c_SomeConstant = 1; // 3
Private
ReadonlyString m_SomeReadOnlyField = "2"; // 4
Private
StaticInt32 s_SomeReadWriteField = 3; // 5
// Type constructor
StaticSomeType () {}// 6
// Instance Constructor
PublicSomeType () {}// 7
PublicSomeType (Int32 x) {}// 8
// Static method and type Method
Public
Static
VoidMain () {}// 9
PublicString InstanceMethod (){
Return
Null;} // 10
// Instance attributes
PublicInt32 SomeProp
{// 11
Get {
Return0;} // 12
Set {} // 13
}
// The indexer with Parameters
PublicInt32
This[String s]
{// 14
Get {
Return0;} // 15
Set {} // 16
}
// Instance event
Public
EventEventHandler SomeEvent; // 17
}
Accessability of type members
CLR terminology |
C # terminology |
Description |
Public |
Public |
Unrestricted access |
Family or Assembly |
Protected internal |
Access is limited to this program or a class derived from this class |
Assembly |
Internal |
Access to this program only |
Family and Assembly |
Not Supported |
|
Family |
Protected |
Access is limited to this class or classes derived from this class |
Private |
Private |
Access is limited |
|
|
|
Static classes can only be used for classes and cannot be used for structures, because CLR always allows Value Type instantiation and cannot be blocked. C # The Compiler imposes the following limitations on static types:
- Static classes must be derived directly from System. Object. It does not make sense to derive from any other base classes.
- The static class cannot implement any interface, because only one instance of the class can be used to call the interface method of the class.
- Static classes can only define static members (fields, methods, attributes, and events). Any instance Member will cause compilation errors.
- Static classes cannot be used as fields, method parameters, or local variables. These variables are instance variables and the compiler reports errors.
Public Static ClassMyStatic
{
/// <Summary>
/// Static field
/// </Summary>
Private Static StringStaticString = "Hello bangq ";
/// <Summary>
/// Static attributes
/// </Summary>
Public Static StringStaticString
{
Get {ReturnStaticString ;}
Set {staticString = value ;}
}
/// <Summary>
/// Static method
/// </Summary>
Public Static VoidSayHello ()
{
Console. WriteLine (staticString );
}
}StaticvoidMain (string [] args) {MyStatic. sayHello (); // Hello bangq MyStatic. staticString = "Hello BangQ"; Console. writeLine (MyStatic. staticString); // hello, BangQ Console. in this case, the static class is a manifestation of the MonoState mode. The Singleton (Singleton) mode is required when MonoState is mentioned. ClassSingleton {// <summary> // static member // </summary> private static Singleton _ instance = null; /// <summary> // static Property // </summary> public static Singleton Instance {get {if (_ instance = null) {_ instance = new Singleton ();} return _ instance ;}} private Singleton () {}// private constructor public void SayHello () {Console. writeLine ("hello bangq"); www.2cto.com} The Singleton mode ensures that there is only one object instance in the system. Generally, you can use a static member and a static attribute. Or a method or a private constructor. To ensure that there is only one instance in the system, you must set the constructor to private in singleton mode, so that you cannot create a New instance. You must obtain the attributes or methods of the instance. So when this code is displayed: Singletonsingleton = new Singleton (); the compiler reports the following error: ConsoleAppDemo. singleton. singleton () 'is inaccessible due to its protection level. If you carefully read the Singleton code above, you can find that the code above may create multiple instances in the case of multithreading, such: when both threads run if (_ instance = null), the first thread creates an instance and the second thread creates another instance. I will summarize the problem of multithreading in the future. Here I will just give you a brief description. It is OK to add a lock. The adjusted code is as follows. /// <Summary> /// lock /// </summary> private static readonly object _ lock = new object (); /// <summary> // static Property // </summary> public static Singleton Instance {get {if (_ instance = null) {lock (_ lock) {if (_ instance = null) {_ instance = new Singleton () ;}}return _ instance ;}} there are many tips and Optimizations in this section, see blog garden Brothers article: http://www.cnblogs.com/BoyXiao/archive/2010/05/07/1729376.html
Next let's talk about the Monostate mode.
publicclassSayHello{privatestringhelloString ="hello wordh";publicSayHello(stringmessage){this.helloString =message;}publicstringHelloString{get {returnhelloString;}set{this.helloString =value;}}}publicclassMonoState{privatestaticSayHelloHello;publicMonoState(){Hello=newSayHello("Hello Word");}publicSayHelloSay{get {returnHello;}set{Hello=value;}}}
Content in the mian Function
Monostate. Say. HelloString = "Hello, BangQ ";
Monostate is another implementation method for obtaining "an object of a certain category in the system is represented as an object". The Singleton mode ensures that the system has only unique instances, while the Monostate mode ensures unique states, of course, the Singleton mode is more used to ensure the unique instance. The Monostate mode focuses more on behavior, that is, behavior consistency. The Singleton mode focuses more on structure and forces a single structure to only generate a unique instance. the content about the design pattern will be discussed in detail later, and then returned to the class members.
Constants and Fields use const to define constants in C #. Since the values of constants do not change, constants are always considered as part of the type definition, and constants are always regarded as static members rather than instance members. The constant value must be determined during compilation. When the code references a constant, it directly extracts the value of the constant and embeds it into the generated IL code. Therefore, you do not need to allocate any memory for the constant during runtime. You cannot obtain the constant address or transmit a constant as a reference. Example in CLR via C #: usingSystem; publicsealedclassSomeLibraryType {public const Int32 MaxEntriesInList = 50;} classProgram {static void Main (string [] args) {Console. writeLine (SomeLibraryType. maxEntriesInList)} using ILSpy, you can see this line of code IL_0XXX: ldc. i4.s 50 proves that const is directly embedded in the IL code. [Note: constants cannot be defined as Static because constants are always implicitly static.] An assembly A defines A constant, assembly B References this constant. When the constant in assembly A changes, only the re-Compilation of assembly B can make the new constant take effect. If you want to obtain a constant at runtime, we recommend that you use a read-only field. A field is a data member that contains an instance of the value type or a reference type. The following table summarizes the field modifiers.
CLR terminology |
C # terminology |
Description |
Static |
Static |
Part of the class status, not part of the Instance status |
InitOnly |
Readonly |
It can only be written by the code in the constructor Method |
Volatile |
Volatile |
The compiler, CLR, or hardware will not perform some "thread-insecure" optimization measures. |
Readonly can also define the constant amount in the system. Unlike const, readonly can be changed in the constructor after the initial value is specified. The value of readonly can also be changed by other means, such as reflection. To sum up, const is a constant for compilation and readonly is the runtime constant. Const is more efficient. As mentioned above, no memory needs to be allocated. We recommend that you use static readonly instead of const.
I would like to summarize the other members of the following class and find that the length is a little too large. I will write it in the next article.
Author: BangQ