C # basic types and member basics as well as constants, fields, and attributes

Source: Internet
Author: User

First, let's vomit about the weather in Hangzhou. It's so hot! Although no sister has been dating me, it is also annoying to stay in the big nest!

Next to C # Basic Types

Type and member Basics

In C #, multiple members can be defined within a type: constants, fields, instance constructors, and type Constructors (static constructors), methods, Operator overloading, conversion operators, attributes, events, types.

Type visibilityYesPublicAndInternal(Default) two types: the type defined by the former is visible to all types in all the assembly, and the type defined by the latter is only visible to all types within the same assembly:

   PublicClass { }                   ExplicitlyInternalClass { }    ImplicitlyInternalClass { }           

Accessibility of members(Arranged from large to small by limit ):

  • PrivateIt can only be accessed by the type of the defined member or by the method in the nested type
  • ProtectedIt can only be accessed by the type of the defined member, the nested type, or the method of the derived type.
  • InternalIt can only be accessed by methods in the same assembly type
  • Protected InternalIt can only be accessed by the type of the defined member, the nested type, the derived type, or the method in the same assembly type (note that the relationship is or here)
  • PublicAccessible by methods of any type in any set of Programs

In C #, if the accessibility of the member is not explicitly declared, the compiler usually chooses Private by default (the one with the largest limit). CLR requires that all the members of the interface type be Public access, C # The Compiler knows this, soProhibit Access to explicitly specified interface members. At the same time, C # also requires that the accessibility of Members cannot be changed when the derived class is rewritten during the inheritance process (CLR does not make this requirement, and CLR allows the restriction to be relaxed when rewriting members ).

Static class

A class that never needs to be instantiated. A static class can only contain static members. In C #, the keyword "static" is used to define a static class, but can only be used to class. It cannot be used to struct, because CLR always allows Value Type instantiation.

C # The Compiler limits static classes as follows:

  • Static classes must be derived directly from System. Object.
  • Static classes cannot implement any interface (because only one instance of the class can call the interface method of the class)
  • A static class can only define static members (fields, methods, attributes, and events)
  • Static classes cannot be used as fields, method parameters, or local variables.
  • After a static class is compiled, a class marked abstract and sealed is generated, and the compiler does not generate an instance Constructor (. ctor method)

Segmented classes, structures, and interfaces

C # The Compiler provides a partial keyword that allows a class, structure, or interface to be defined in multiple files.

During compilation, the compiler automatically combines all parts of the class, structure, or interface. This is only a function provided by the C # compiler, and CLR knows nothing about it.

Constant

A constant represents a constant value. For example, we define the circumference rate 3.12415926 as a PI constant to make the code easier to read. And constants are substituted into the computation during compilation (A constant is a symbol. during compilation, the compiler replaces the symbol with the actual value.), Will not cause any performance loss. However, this may also cause a version problem, that is, if we modify the value represented by constants in the future, recompile all the places where this constant is used (I personally think this is also the origin of the constant name, we shouldConstantThe value is defined as a constant to avoid version issues during later changes ). The following example also demonstrates this. The constant operations in the Test1 and Test2 methods are completed after compilation.

From the above example, we can also see that constant keys and values are static members after compilation, because constants are usually associated with types rather than instances. Logically,Constant is always a static member. But for constants defined within a method, due to the limitation of the scope, it is impossible to reference this constant outside of the method. Therefore, after compilation, the constant is optimized.

Field

A field is a data member. In OOP design, a field is usually used to encapsulate an internal state of a type, and the method represents operations on these States.

The modifiers available for fields in C # are:

  • StaticDeclared fields and types are associated, rather than objects (by default, fields and objects are associated)
  • ReadonlyDeclared fields can only write values in the constructor (can be modified through reflection)
  • VolatileDeclared fields are easy to lose (used in multi-threaded environments)

Note that when a field is marked as readonly, the reference is not the reference value. Example:

              [] chars =  [] { , ,             chars[] = ] = ] =             chars =  [] { , , 
Attribute

CLR supports two attributes: No parameter attribute and parameter attribute (called the indexer in C ).

One of the important principles of object-oriented design and programming isData encapsulationThis means that the field (the internal state of the encapsulated object) should never be made public. Therefore, CLR provides an attribute mechanism to access field content (If you enter propfull in VS and add the Tab twice, the code snippet of the field and attribute will be automatically generated for us.).

In the following example, a Person object contains an age field. If this field is directly published, the object cannot be saved and the age is not set to 0 or 1000, this is obviously meaningless (it also damages Data encapsulation). Therefore, you can add some additional logic when operating fields through attributes to ensure data validity.

                    {  (value >  && value <= ) age = { }    

After the above Code is compiled, the compiler will actually generate a method for each get and set accessors in the property. The method name is get _ and set _ and the attribute name is added.Attribute is actually a method..

If you create an attribute to encapsulate a field, C # also provides us with a simpler syntax calledAutomatically implemented attributes(AIP ). The following is an example (Input the prop TAB twice in VS to generate an AIP segment for us.):

Note that AIP supports fields automatically generated by the compiler, and the name may be changed every time the compiler compiles. ThereforeDo not use any types to be serialized or deserializedAIPFunction.

Object and set Initiator

In implementation programming, we often construct an object and set some common attributes or fields of the object. Therefore, C # provides us with a simplified syntax to complete these operations. Example:

              Name { ;   Id { ;   Age { ;             Person p1 = = = =             Person p2 =  Person() { Id = , Name = , Age = 

When using the object initializer syntax, the code generated by the compiler for us is actually the same as the above, but the following code is obviously more concise. If the parameter-free constructor is to be called, C # also allows us to omit the parentheses before braces:

Person p2 =  Person { Id = , Name = , Age =  };

If an attribute type implements the IEnumerable or IEnumerable <T> interface, this attribute is considered to be a set, and we initialize a set using similar syntax. For example, we add a new Skills attribute to the Person class in the above example.

 List<> Skills { ; ; }

Then you can use the following syntax to initialize

Person p3 =  Person { Id = , Name = , Age = , Skills =  List<> { ,  } };

Here, we use the new List <string> {"C #", "jQuery"} sentence to initialize a set (the new List <string> can be omitted in implementation, the compiler automatically infers the set type based on the attribute type) and adds two records. The code generated by the compiler looks like this:

p3.Skills =  List<>);
Anonymous type

Sometimes, we need to encapsulate a set of data, only attributes or fields, there is no method, and only for the current program, not reuse between projects.

If we follow the traditional practice, we need to manually define a class to encapsulate this set of data. The anonymous type provides a convenient method to encapsulate a set of read-only attributes into a single object without explicitly defining a type. Example:

We can see from the above example that we only wrote one sentence

 obj =  { Id = , Name = , Addr =  };

The compiler will do a lot of work for us. First, define a type for US (the type name is generated only when the compiler is compiled, and it is unknown during programming, so it is called an anonymous type ), the data type contains three attributes: Id, Name, Addr, and corresponding supported fields. At the same time, three get accessors are generated, and no set accessors are generated (DescriptionAnonymous attributes are read-only.).

In addition, in the Main method, because we do not know the type name during programming, we mustUseVarKeyword to make the compiler recommend the type(Object or dynamic can also be used, but this is completely meaningless ). By checking the IL Code Compiled by Main, we can also find that the initialization of the anonymous type is completed by calling the parameter constructor of the anonymous type, this is also different from the previous one (because the anonymous type attribute is read-only, the attribute value cannot be set after initialization by calling the non-parameter initiator, the compiler does not generate a non-argument constructor of the anonymous type ).

Parameter attributes

All the attributes mentioned above have no parameters. in implementation, there is also an attribute that can contain parameters, called the property with parameters (called the indexer in C ).

     =  [          [== ] = ] =  ss = array[] + array[

In the above example, unlike defining the parameter-free attribute, there is no attribute name,UseThis [Parameters]Syntax to define a property with parameters (Indexer)This is the requirement of C. Unlike the parameter-free attribute, the parameter-free attribute can be reloaded:

                  [ {  { array[index] =          [ index,  (isStartFromEnd)  array[ -  (isStartFromEnd) array[ - index] = array[index] =

The attribute is essentially a method, and the same is true for a parameter property (for CLR, it is a method call even if there is no parameter or no parameter ), so what is the IL generated after compilation with the parameter attribute? In fact, C # is named get_Item and set_Item by default for all IL methods generated with parameter attributes. Of course, you can apply System. runtime. CompliserServices. IndexerNameAttribute To The indexer to modify this default behavior.

Attribute Accessability

The get and set accessors of properties can define different accessors. If the accessibility of the get and set accessors is different, C # The minimum limit must be specified for the attribute.

   {   { name =

NOTE: If both get and set access is set, the system will prompt "You cannot specify the accessable modifier for both accessors of the attribute ", access modifiers for attributes or indexers are subject to the following conditions:

  • You cannot use accessors for interfaces or explicit interface members.
  • Only when the property or indexer hasSetAndGetThe accessors modifier can be used only when the accessors are used. In this case, only the modifier can be used for one of the accessors.
  • If the attribute or index appliance has an override modifier, The accesser modifier must match the accesser's Accessability (if any) of the rewritten accessors.
  • The Accessibility level of the accesser must be more restrictive than the Accessibility level of the attribute or the indexer.
End

I moved books and typed Code while writing blog posts. I sat down for nearly a day without knowing it ~ I want to go out for an activity ).

The capability level is limited. This blog post is mainly for the purpose of self-Summary. If there is any error in this article, please point it out. Thank you!

Reference

1. CLR Via C #

2. Asymmetric accessors

 

 

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.