The seventh domain and attributes of C # sharp experience

Source: Internet
Author: User
Tags abstract constant constructor inheritance integer interface variables variable

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.csusing system;namespace mynamespace1{public class Myclass1{public static readonly int myField = 10;}} File2.cs//csc/r:file1.dll file2.csusing 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 + +.

Property

Attributes can be said to be an innovation in the C # language. Of course, you can also say no. The reason is that the implementation behind it is actually still two functions--an assignment function (get), a value function (set), which can be clearly seen from the intermediate language code it generates. The reason is that it is true that object-oriented programming has always been a special interface to the OO-style class of "attribute" in the language level. Understanding the design of attributes is the root of the tool we use with good attributes. C # does not advocate setting the protection level of the domain to public and allowing users to manipulate outside the class--that's too oo, or too insecure! For all fields that are necessary to be visible outside the class, C # is recommended for use in attributes. Property does not represent a storage location, which is a fundamental difference between a property and a domain. The following is a typical property design:

Using system;class myclass{int integer;public int integer{get {return integer;} set {Integer=value;}}} Class Test{public static void Main () {MyClass myobject=new MyClass (); Console.Write (Myobject.integer); myobject.integer++; Console.Write (Myobject.integer);}
As we expect, the program outputs 0 1. We can see that the attributes provide a friendly interface for the domain members to the programmer by wrapping the method. The value here is the keyword of C #, the implied parameter of set when we perform the property operation, which is the right value when we execute the property write operation.

Property provides read-only (get), write-only (set), read-write (get and set) three interface operations. For these three operations of the domain, we must declare them in the same property name, not separate them, and see the following implementation:

Class Myclass{private string Name;public string name {get {return name;}} public string Name {set {name = value;}}}
The above method of separating the name attribute implementation is wrong! We should put them together as in the previous example. It is worth noting that three attributes (read only, write only, read and write) are considered by C # to be the same attribute name, as shown in the following example:

class myclass{protected int Num=0;public int num{set {num=value;}}} Class Myclassderived:myclass{new public int num{get {return Num;}}}  Class Test{public static void Main () {myclassderived MyObject = new myclassderived ();//myobject.num= 1; Error! ((MyClass) MyObject).   Num = 1; }}
We can see that the attribute in myclassderived num-get{} masks the definition of the attribute num-set{} in MyClass.

Of course, the attribute is far more than just the domain interface operation, the nature of the property or method, we can according to the program logic in the extraction or assignment of attributes to some check, warning, and other additional operations, see the following example:

Class Myclass{private string Name;public string name {get {return name;} set {if (value==null) name= "Microsoft"; elsename=value;}}}
Because of the nature of the method of the attribute, there are of course various modifications of the method. Property also has 5 access modifiers, but the access modification of the property is often public, otherwise we lose the meaning of the property as the common interface of the class. In addition to the method of the multiple parameters of the method overload and other attribute attributes do not have, virtual, sealed, override, abstract and other modifiers on the property and method of the same behavior, but because the attribute is implemented in essence two methods, some of its behavior needs our attention. Look at the following example:

Abstract class A{int y;public virtual int X {get {0;}} public virtual int Y {get {return y;} set {y = value;}} public abstract int Z {get; set;}} Class B:a{int z;public override int X {get {return base. X + 1; }}public Override int Y {set {base. Y = value < 0? 0:value; }}public override int Z {get {z;} set {z = value;}}}
This example focuses on some typical behavior of attributes in an inheritance context. Here, Class A has to be declared abstract because of the existence of the abstract property Z. Subclass B refers to the properties of the parent class A through the base keyword. A virtual property in Class A can be overridden by Y-set in class B.

static properties and static methods can only access static domain variables of a class. We can also declare external properties as we do external methods.



Related Article

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.