Class and structure (1), structure (

Source: Internet
Author: User
Tags protected constructor

Class and structure (1), structure (

Classes and structures are actually templates for creating objects (instances). Each object contains data and provides methods to process and access data.

Class defines the data and functions that each object of a class can contain.

 

class PhoneCus    {        public const string DaySend = "Mon";        public int CusId=;    }

 

The difference between structures and classes is the way they are stored in the memory, the way they are accessed and some of their features (the differences will be detailed later ).

The structure of small data types can improve the performance. The syntax is similar. The main difference is that the structure is declared using the keyword struct instead of class.

 

    struct PhoneCusStruct    {        public const string DaySend = "Mon";        public int CusId=;    }    

For classes and structures, the instance is declared using new: This keyword creates an object and initializes it.

 

PhoneCus myCus = new PhoneCus();PhoneCusStruct  myCus2 = new PhoneCusStruct();

 

In the preceding example, the Field Values of the class and structure are both 0 by default.

I. Category

The data and functions in a class are called class members (data members and function members ).

1. Data Member

A data member is a member of the data-fields, constants, and events that contain classes. The data member can be static data. Class Members are always instance members, unless they are declared using static display.

2. Function Member

Function members provide certain functions for operating data, including methods, attributes, constructors, Terminators, operators, and indexes.

(1) Method

* C # differentiate functions and methods. C # contains the above mentioned functions.

* PASS Parameters to methods

Parameters can be passed to methods by reference or value. When a variable is passed to a method through reference, the called method gets this variable, and the correct pointer is the pointer to the variable in the memory. Therefore, any change to the variable in the method is still valid after the method exits.

If a variable is passed to the method through a value, the called method returns an identical copy of the variable. That is to say, after the method exits, modifications to the variable will be lost.

For complex data types, transferring by reference is more efficient, because a large amount of data must be copied during value-based transmission.

Note that the behavior of a string is different because the string is immutable, so the string cannot use the behavior of the general reference type. In method calls, changes made to the string do not affect the original string.

* Ref Parameters

As shown in the preceding example, the default value type is used to pass variables through values. However, you can also force the value parameter to be passed to the method through reference. Therefore, the ref keyword is used. In this way, any changes made to the variable by this method will affect the original value.

        static void SomeFunction(int[] ints,ref int i)        {            ints[0] = 100;            i = 100;        }        

When calling this method, you must add the ref keyword.

SomeFunction (ints, ref I );

* Out Parameters

C # requires that the variable be initialized with an initial value before being referenced. However, using the out keyword for initialization can simplify the initialization of input parameters insisted on by the C # compiler.

When the out prefix is added before the input parameters of the method, the variables passed to the method can not be initialized. The variable is passed through reference, so any changes made to the variable by the corresponding method will be retained when the variable is returned from the called method.

When calling this method, you still need to use the out Keyword:

        static void SomeFunction(int[] ints,out int i)         {                ints[0] = 100;                 i = 100;         }        SomeFunction(ints, out i);       

 

 

* Named Parameters

Parameters are generally transmitted to methods in the defined order. Naming parameters can be passed in any order.

        string FullName(string firstName,string lastName)    {        renturn firstName+" " +lastName;     }    

Call method:

            FullName("John","Doe");        FullName(lastName:"Doe",firstName:"John");

* Optional parameters

Parameters can also be optional. The default value must be provided for optional parameters. Optional parameters must also be the last parameter of the method definition.

        void TestMethod(int notOption,int option = 10)        {            Console.WriteLine( notOption + option);        }        

* Method Overloading

C # method Overloading is supported-several versions of the method have different signatures (the method names are the same, but the number and/or type of parameters are different ).

        class MathTest          {             public int Value;             public int GetSquare()             {                    return Value*Value;             }             public  int GetSquare(int x)             {                return x*x;             }          }

 

Some restrictions on parameters of the overload method:

The two methods cannot be different only in the return type;

The two methods cannot be distinguished only based on whether the parameter is declared as ref or out.

For method overloading in any language, if an incorrect overload method is called, a running error may occur. (We will discuss how to avoid these errors later ).

(2) property)

Attribute is a method or a pair of methods. In the client's opinion, it is a field.

Public string SomeProperty {get {return "value";} set {// set attribute value }}

The get accessor does not contain any parameters and must return the type of the attribute declaration. You should not specify any display parameters for the set accessors. the compiler will

Assume that it has a parameter. The type of the device may have the same attributes and is expressed as value.

        private int age        public int  Age        {            get            {                return age;            }            set            {                age = valeu;            }        }

Note that the naming conventions are C # case-sensitive and use the same name, but the public attributes are named in uppercase. If an equivalent private field exists, it is named in lower case.

Some developers prefer to use the field names prefixed with underscores, such as _ age, which greatly facilitates field recognition.

 

* Read-only and write-only attributes

If the set accessor is omitted in the attribute definition, the read-only attribute is created. In this way, the client code can only read the value of this attribute, but cannot set the value.

        private int age        public int  Age        {            get            {                return age;            }        }

Similarly, if the get accessors are omitted in the attribute definition, only the attributes are created.

* Attribute access modifier

C # allow different access modifiers for the gei and set accessors of the attribute. Therefore, the attribute can have public get accessors and protected set accessors.

In gey and set accessors, there must be an access level (public) with attributes ).

* Automatically implemented attributes

If the set and get accessors of the attribute do not have any logic, you can use the automatically implemented attribute. This attribute automatically implements the back member variable.

        public int  Age        {            get;            set;        }

You do not need to declare private int age; the compiler will automatically create it.

When an automatically implemented attribute is used, the validity of the attribute cannot be verified in the attribute settings. However, there must be two accessors. The attribute cannot be set to read-only or write-only.

Public int Age

{

Get; // Error

}

However, the access level of each accesser can be different,

Public int Age

{

Get;

Private set;

}

 

(3) constructor

Declaring a basic constructor is to declare a method with the same name as the contained class, but this method does not return a value.

Public class MyClass

{

Public MyClass ()

{

}

//

}

Generally, if no constructor is provided, the compiler creates a default constructor in the background. This is a basic constructor. It can only Initialize all member fields as the standard default values. This is usually enough, otherwise you need to write your own constructor.

The overload of constructors is the same as that of other methods. The constructor can provide any number of reloads, as long as their signatures are significantly different.

        public class MyClass        {            public MyClass()            {            }            public MyClass(int i )            {                / /            }            //        }

If a constructor with parameters is provided, the compiler will not automatically provide the default constructor. The compiler automatically provides the default constructor only when no constructor is defined.

        public class MyNum        {            private int number;            public MyNum(int number)            {                this.number  =number;            }        }

 

This keyword is generally used to distinguish between a member field and a parameter with the same name.

If you try to instantiate an object using a constructor without parameters, an error is returned:

MyNum num = new MyNum (); // Error

You can define constructors as private or protected so that irrelevant classes cannot access them:

        public class MyNum        {            private int number;            private MyNum(int number)            {                this.number  =number;            }        }

 

The above example does not define MyNum as any public or protected constructor. This prevents MyNum from being instantiated in external code using the new operator, but you can compile a public static attribute or method in the MyNum class to instantiate the class.

This is useful in the following two cases:

Class is only used as a container for some static members or attributes, so it will never be instantiated.

You want the class to be instantiated only through a static member function.

 

* Static Constructor

C # You can write a static constructor without parameters for the class. This constructor is executed only once, and the previous constructor is an instance constructor. If you create an object of the class

Run it.

Class MyClass

{

Static MyClass ()

{

}

}

One reason for writing a static constructor is that the class has some static fields or attributes. You need to initialize these static fields and attributes from the external source before using the class for the first time.

The. NET Runtime Library cannot ensure when to execute static constructor, so the code that requires execution at a specific time cannot be placed in static constructor. It cannot predict the sequence in which the static constructors of different classes are executed. However, you can ensure that the static constructor runs at most once and calls it before the code references the class.

In C #, a static constructor is usually executed before any member of the class is called for the first time.

Note that the static constructor does not have an access modifier and other C # code never calls it. NET Runtime Library calls it, So access modifiers such as public and private do not make any sense. For the same reason, a static constructor cannot contain any parameters, and a class can have only one static constructor. Obviously, static structures can only access tired static members, but cannot access instance members of the category.

The instance constructor and static constructor without parameters can be defined in the same class at the same time. Although the parameter list is the same, this is not a conflict. Because the static constructor is executed when the class is loaded and the instance constructor is executed when the instance is created, no constructor conflict will be executed when the class is loaded.

If any static fields have default values, specify them before calling the static constructor.

The following demonstrates the usage of static constructor:

Class MainEntryPoint

{

Static void Main ()

{

Console. WriteLine ("UserPreference: BackColor is" + UserPreference. BackColor. ToString ());

}

}

Class UserPreference

{

Public static readonly Color BackColor;

Static UserPreference ()

{

BackColor = Color. Red;

}

Private UserPreference ()

{

}

}

The static variable is initialized in the static constructor.

* Call other constructors from Constructors

Sometimes there are several constructors in a class that contain some common code.

Class Car

{

Private string des;

Private int nWheels;

Public Car (string des, int nWheels)

(

This. des = des;

This. nWheels = nWheels;

)

Public Car (string des)

(

This. des = des;

This. nWheels = 4;

)

}

The two constructors initialize the same field. Obviously, it is best to put all the code in one place. C # has a special syntax called constructor.

Class Car

{

Private string des;

Private int nWheels;

Public Car (string des, int nWheels)

(

This. des = des;

This. nWheels = nWheels;

)

Public Car (string des): this (des, 4)

(

)

}

Here, the this keyword only calls the most matched constructor. The constructor executes the constructor before the constructor.

C # The constructor can call another constructor of the same class, or call a constructor of the direct base class. The same syntax is used, however, the base keyword of the application replaces this. there cannot be multiple calls in the initiator.

 

3. Read-Only Fields

A constant is a variable that contains a value that cannot be modified. But constants do not have to meet all requirements. Sometimes some variables are needed, and their values should not be changed, but their values are unknown before running. C # provides another type of variable for this situation: Read-Only field (readonly ).

The readonly keyword is much more flexible than the const keyword. A field can be set as a constant, but some calculations can be executed to determine its initial value.

The rule is to assign values to read-only fields in the constructor, but not elsewhere. The read-only field can also be an instance field, and each instance of the class can have different values.

Unlike const, to set a read-only field to static, it must be displayed and declared.

 

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.