(Post) Open the C # door const, readonly, and static

Source: Internet
Author: User
Tags constant definition

V. Const, readonly, and static

In section 4, I introduced the definition of constants. the keyword is const. When defining a constant, you must assign its initial value. Once an initial value is assigned, the value cannot be modified. That is, the meaning that the constant value cannot be changed. Since C # is a pure object-oriented language, there is no constant or variable outside of the object. Therefore, these definitions must be completed within a type.

In addition to using constants as temporary constant values of some algorithms, the most important thing is to define some global constants, which are directly called by other objects. The best type of the constants in the set is struct (structure ). I will explain in detail about struct in the following sections. Here I will only give an example of the usage of constants. For example, if we need to use FTP in. net, some specific FTP code can be defined in this way, as shown below:
Public struct ftpcode
{
Public const string connectok = "220 ";
Public const string requiredpassword = "331 ";
Pubconst string loginok = "230 ";
Public const string pasvok = "227 ";
Public const string cwdok = "250 ";
Public const string pwdok = "257 ";
Public const string transferok = "226 ";
Public const string listok = "150 ";
Public const string porttok = "200 ";
Public const string nofile = "550 ";
}

To use these constants, you can call them directly, for example, ftpcode. connectok. If the structure ftpcode is only used inside the assembly, you can also set the structure type and internal constants to internal. Using this method has three advantages:
1. centralized management of global constants for easy calls;
2. It is easy to modify. Once the specific FTP code changes, you only need to modify the constant value in ftpcode. Other codes are not affected;
3. Easy to expand. To add new FTP code, you can directly modify the ftpcode structure. The remaining code is not affected.

Although the value of a variable can be modified, we can also define a read-only variable by adding the keyword readonly when defining it. Definition:
Public readonly int number = 20;

The value of the variable number is read-only at this time, and it cannot be re-assigned. When defining a read-only variable, we recommend that you assign the initial value to the variable. If no initial value is assigned,. NET will give a warning and assign different initial values based on their types. For example, if the initial value of int type is 0 and that of string type is null. Because the value of a defined read-only variable cannot be modified, the definition of a read-only variable without an initial value does not have any meaning, but is prone to exceptions of null reference objects.

The significance of static is different from that of const and readonly. Const is only used for constant definition, readonly is only used for variable definition, while static is irrelevant to constants and variables. It means that the defined value is related to the type, but not the object state.

As I have mentioned earlier, the so-called "object" can be called a type instance. Taking the class type as an example, after defining a class type, you need to create an object of this type, it must be instantiated. You can call its attributes or methods. For example, the name, password, signin, and signout methods of the user type are all related to objects. To call these attributes and methods, you can only call them by instantiating objects, as shown below:
User user = new user ();
User. Name = "Bruce Zhang ";
User. Password = "password ";
User. signin ();
User. signout ();

However, when defining a class member, we can also use the static keyword to define some class members irrelevant to the object state, such as the following code:
Public class logmanager
{
Public static void logging (string logfile, string log)
{
Using (streamwriter logwriter = new streamwriter (logfile, true ))
{
Logwriter. writeline (log );
}
}
}
The logging method is a static method, which has nothing to do with the object state of the logmanager class. Therefore, you do not need to create a logmanager instance when calling this method:
Logmanager. Logging ("log.txt", "test .");

The so-called "irrelevant to object state" also needs to be discussed from instantiation. When instantiating a class type, you actually allocate a space in the memory to create the object and store some values of the object, such as name and password. If there are no special restrictions on the same class type, you can create multiple objects at the same time. These objects are allocated to different memory spaces, and their types are the same, but it has different object states, such as the memory address, Object Name, and values of each member in the object. For example, we can create two user objects at the same time:
User user1 = new user ();
User user2 = new user ();

Because the name and password attributes are closely related to objects, the implementation of the Methods signin and signout also calls the internal name and password attribute values, so they are also closely related to objects, therefore, these Members cannot be defined as static members. If you set both the name and password attributes as static attributes, you can only set the values as follows:
User. Name = "Bruce Zhang ";
User. Password = "password ";

Obviously, the name and password set at this time are irrelevant to the instance user, that is, no matter how many user instances are created, the name and password do not belong to these instances, this is obviously contrary to the meaning of the user class. The same applies to Methods signin and signout. Of course, we can also change the method definition so that the method can be defined as static, as shown below:
Public class user
{
Public static void signin (string username, string password)
{
// Code omitted
}
Public static void signout (string username, string password)
{
// Code omitted
}
}

Because the name and password values required for the signin and signout methods are changed to pass in from the method parameters, the two methods have no relationship with the object state. The call methods of the defined static method are slightly different:
User user = new user ();
User. Name = "Bruce Zhang ";
User. Password = "password ";
User. signin (user. Name, user. Password );
User. signin (user. Name, user. Password );

Two-phase comparison, such modifications lead to inconvenience in use. Therefore, when a method is closely related to the object state, it is best not to define it as a static method.

So why do I define all the logging methods as static methods in the logmanager class? This is because this method does not have much to do with the object state. If the logfile and log parameters of the method are defined as the attributes of the logmanager class, it is unreasonable in actual use, it will also cause inconvenience in use. The most important thing is that once a non-static method is called, it is inevitable to create an instance object. This will cause unnecessary memory space waste. After all, the logmanager type is only used by the caller in the logging method, but does not have much to do with the object status. Therefore, you do not need to create an instance to call this method. This is completely different from the user type.

In a class type definition, both static members and non-static members can be allowed. However, in a static method, you cannot directly call a non-static method of the same type, as shown below:
Public class test
{
Private void foo1 ()
{
// Code omitted;
}
Public static void foo2 ()
{
Foo1 (); // error;
}
Public void foo3 ()
{
Foo1 (); // correct;
}
}

In the static method foo2, If you directly call the private non-static method foo1 under the same type of test, an error will occur. The call of the non-static method foo3 to foo1 is correct. To call the foo1 method correctly in the static method foo2, you must create an instance of the test class and use it to call the foo1 method. The modification is as follows:
Public static void foo2 ()
{
Test test = new test ();
Testfoo1 (); // correct;
}

In the foo2 method, the test instance is created and the foo1 method is called through the Instance Object test. Note that although the foo1 method is a private method, the foo2 method itself is in the test object, so the private method foo1 can be called at this time, because object encapsulation is only for external callers, it can be called for internal types, even private.
 
Static attribute members of the type have the same restrictions as static methods. After all, basically, the type attribute is actually two get and set methods.

If a static field is defined in the class, there are two ways to initialize it. First, initialize fields during definition, or assign initial values to these static fields in the Type constructor. For example:
Class explicitconstructor
{
Private Static string message;
Public explicitconstructor ()
{
Message = "Hello World ";
}
Public static string message
{
Get {return message ;}
}
}
Class implicitconstructor
{
Private Static string message = "Hello World ";
Public static string message
{
Get {return message ;}
}
}

In the class explicitconstructor, the constructor is used to initialize the value for the static field message, while in the class implicitconstructor, the message static field is initialized directly during definition. Although both methods can achieve initialization purposes, the latter has obvious performance advantages (interested, can read an article on my blog http://wayfarer.cnblogs.com/archive/2004/12/20/78817.html ). Therefore, we recommend that you initialize static fields directly.

If no value is set for a static field,. NET will give a warning and assign different initial values based on different types. In addition, static can be used together with readonly to define a read-only static variable. However, static cannot be applied to the definition of constants.

In C #1. X, static cannot be used to modify the class type. That is to say, we cannot define a static class. However, for a class type, if all its members are static members, it is meaningless to instantiate the class at this time. In this case, we often set the constructor to private and set its class to sealed (sealed indicates that the class cannot be inherited, and sealed will be introduced later ). In this way, you can avoid class instantiation operations, such as the previously defined logmanager, that is, you can modify the definition:
Public sealed class logmanager
{
Private logmanager ()
{}
Public static void logging (string logfile, string log)
{
Using (streamwriter logwriter = new streamwriter (logfile, true ))
{
Logwriter. writeline (log );
}
}
}

C #2.0 supports the definition of static classes. The method is to add the static keyword before the class, such:
Public static class logmanager {}

Static classes do not support instantiation. Therefore, you cannot add sealed or abstract keywords in the definition of static classes, or inherit a class or be inherited by a class, the class can only be a static member and cannot define the constructor. Because there is no inheritance relationship between classes, you cannot use protected or protected Internal as the access restriction modifier in static class members.

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.