C # Sharp Experience (vii)

Source: Internet
Author: User

Seventh lecture fields and attributes

Domain

A field (field), also known as a member variable (Variable), represents a storage location and is an integral part of the class in C #. The type of the field can be any data type in C #. However, for those other reference types that drop string types because of the operation that involves some class constructors during initialization, we will not mention this part as "nesting of Classes" in "Interface Inheritance and polymorphism".

Domains are divided into instance domains and static domains. An instance field is a specific object that is proprietary to a particular object. A static field belongs to a class and is shared by all objects. C # strictly stipulates that instance fields can only be obtained through objects, and static fields can only be obtained through classes. For example, we have a type MyClass object Myobject,myclass the instance domain Instancefield (access limited to public) can only be obtained: MyObject. Instancefield. The MyClass static domain Staticfield (access restriction is public) can only be obtained as follows: Myclass.staticfield. Note that static fields cannot be retrieved by objects like traditional C + +, which means that Myobject.staticfield is not used incorrectly and cannot be compiled through the compiler.

The access restriction of domain embodies the encapsulation principle of object-oriented programming. As mentioned earlier, there are 5 types of access restriction modifiers in C #, and these 5 apply to the domain. C # only expands the original friend modifier of C + + with internal. When it is necessary to make certain domains of two classes visible to each other, we declare the fields of these classes as internal and then compile them in a composite body. If you need to be visible to their inheriting subclasses, declare protected internal. This is actually what the composition means--encapsulating the combination of logically related classes.

C # introduces the ReadOnly modifier to represent a read-only field, and a const to represent invariant constants. What is the difference between the name of a read-only domain and the immutable constants cannot be modified? A read-only domain can only be assigned in the process of initializing--declaring initialization or constructor initialization--the assignment of read-only fields cannot be performed elsewhere, otherwise the compiler will complain. A read-only domain can be either an instance field or a static field. The type of a read-only field can be any type of C # language. However, the const-modified constants must be assigned at the same time as the declaration, and require the compiler to compute the determined value at compile time. A const-decorated constant is a static variable and cannot be obtained for an object. The type of a const-decorated value is also restricted, and it can only be one of the following types (or can be converted to the following types): SByte, Byte, short, ushort, int, uint, long, ulong, char, float, double, decimal , bool, string, enum type, or reference type. It is noteworthy that the reference type here, because all types outside of the string type are outside of the null value, the compiler cannot compute their exact values at compile time, so the reference type that we can declare as const can only be a string or other reference type with a value of NULL. Obviously when we declare a null constant, we have lost the meaning of the declaration--which can be said to be the embarrassment of C # design!

This means that when we need a const constant, but its type restricts it from being able to compute a definite value at compile time, we can take it as a static readonly to solve. But there is a slight difference between the two. Look at the following two different files:

//file1.cs
//csc /t:library file1.cs
using System;
namespace MyNamespace1
{
public class MyClass1
{
        public static readonly int myField = 10;
    }
}
//file2.cs
//csc /r:file1.dll file2.cs
using System;
namespace MyNamespace2
{
public class MyClass1
{
        public static void Main()
        {
Console.WriteLine(MyNamespace1.MyClass1.myField);
        }
    }
}

Our two classes belong to two files File1.cs and File2.cs, and are compiled separately. When the domain MyField declared as static readonly in the file File1.cs, if we change the MyField value to 20 because of a need, We just recompile the file File1.cs as File1.dll and we get 20 when we execute file2.exe. But if we change the static readonly to const and then change the initialization value of the MyField, We have to recompile all the files referenced to File1.dll, otherwise the MyNamespace1.MyClass1.myField we quoted will not change as we wish. This is particularly noticeable in the larger system development process. In fact, if we can understand that const-modified constants are computed at compile time, the values are determined. and replace it with every place that references the constant, and the amount that is determined at run time when ReadOnly--just after initialization we don't want its value to change again, we can understand the hard work of the C # designers. , we can completely grasp the const and readonly behavior!

Domain initialization is an issue that requires special attention in object-oriented programming. The C # compiler defaults to initializing each field to its default value. Simply put, the default value for a numeric type (enumerated type) is 0 or 0.0. The default value for the character type is ' \x0000 '. The default value for a Boolean type is false. The default value for the reference type is null. The default value for a struct type is the corresponding default value for all types inside it. Although the C # compiler sets the default type for each type, as an object-oriented design principle, we still need to initialize the variables correctly. In fact, this is also the practice recommended by C #, where no initialization of the domain causes the compiler to issue a warning message. In C # There are two places to initialize a domain--the declaration is both initialized and initialized within the constructor. As mentioned earlier, the declaration initialization of a domain is actually executed by the compiler as an assignment statement at the very beginning of the interior of the constructor. Instance variable initialization is placed inside the instance constructor, and static variable initialization is placed inside the static constructor. If we declare a static variable and initialize it at the same time, then the compiler will construct a static constructor for us to put the initialization statement into an assignment statement. As a const-modified constant field, which cannot be counted as an initialization statement in a strict sense, we can treat it like a macro substitution in C + +.

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.