[. NET] textbook C # (2)-. NET resource hosting,

Source: Internet
Author: User
Tags finally block

[. NET] textbook C # (2)-. NET resource hosting,
Objective C # (II)-. NET resource hosting

Avoid using the member initializer:

(1) When you want to initialize an object as 0 or null. Because the system's default initialization work (before all code is executed) will set everything to 0 or null, we do a step of extra operations. In addition, if it is a value type, the performance is very poor.

MyValueType myVal1; // Initialization is 0 MyValueType myVal2 = new MyValueType (); // It is also 0

These two statements initialize the variable to 0, but the first one is implemented by setting the memory containing myVal1 to 0, and the second one is the IL command of initobj, this results in a binning operation on the myVal2 variable, which takes additional performance and time.

(2) perform different initialization methods for the same variable:

Class Program {// <summary> // declare and initialize /// </summary> private List <string> _ lables = new List <string> (); public Program () {} public Program (int capacity) {_ lables = new List <string> (capacity );}}

If the constructor with capacity is used to initialize the class, the List <string> Object indicates that the class is initialized twice, and the first class becomes a junk object.

(3) Suitable reasons to put the initialization code in the constructor: try-catch can facilitate Exception management.

 

13. initialize static member variables correctly

1. Before using a type instance, you should initialize all static member variables of this type. A static constructor is a special function that will be executed before all other methods, variables, or attributes are accessed for the first time. You can use this function to initialize static variables and perform operations such as Singleton mode.

2. Static initializes and static constructors are the best choice for static members of the initialization class.

3. The most common reason for using a static constructor instead of a static initiator is to capture and handle exceptions.

 

Iv. Minimize repeated initialization Logic

1. if multiple constructors contain similar logic, we should extract them to a common constructor to avoid code duplication, you can also use the constructor to generate more efficient code.

    class MyClass    {        private List<string> _lables;        private string _name;        public MyClass() : this(0, string.Empty)        {        }        public MyClass(int capacity = 0, string name = "")        {            _lables = new List<string>(capacity);            _name = name;        }    }

The second constructor uses "" to give the default value of name instead of string. empty, because string. empty is not a constant during compilation, but a static attribute defined in the string class, so it cannot be used as the default value of the parameter.

2. Operation Sequence when the first instance of a type is created:

(1) set static variables to 0;

(2) execute the static variable initiator;

(3) execute static constructors of the base class;

(4) execute static constructor;

(5) set the instance variable to 0;

(6) execute the instance variable initiator;

(7) execute the appropriate instance constructor in the base class;

(8) execute the instance constructor.

3. Use the initializer to initialize simple resources and use constructor to initialize members that require complex logic. Do not forget to extract calls to a constructor to reduce duplication.

4. In the constructor definition, only one initiator can be used, either This () is used to delegate to another constructor, or base () is used to call the constructor of the base class.

 

15. Use using and try/finally to clear Resources

1. the type of the resource that uses an unmanaged system must be displayed and released Using the Dispose () of the IDisposable interface. The Using () Statement will generate a Try/finally block.

 

16. Avoid creating unnecessary objects

1. GC can manage the memory well, but no matter how efficient it is, it will take a long time to allocate and destroy objects on the stack. If you create too many referenced objects, this will have a serious impact on the performance of the program.

Public void Paint () {using (var myFont = new Font ("Arial", 10.0f) {Console. WriteLine ($ "use {myFont} for painting ");}}

If this method is frequently called. Each call creates another Font object, but it contains exactly the same content as before. GC cleans up the garbage for you every time, which is obviously very inefficient.

The myFont can be upgraded to a static variable.

Private readonly static Font _ myFont = new Font ("Arial", 10.0f); public void Paint () {Console. WriteLine ($ "painting with {_ myFont ");}

2. Reduce the number of objects created in the program.

(1) promote common local variables to member variables;

(2) provides a class to store the singleton object of a common instance of a type.

3. Use StringBuilder to perform complex string operations

 

VII. Implementation of standard destruction Models

1. The following four tasks must be completed in the implementation of the IDisposable. Dispose () method:

(1) release all unmanaged resources;

(2) release all managed resources, including the release of event listening programs;

(3) set a status flag to indicate that the object has been destroyed;

(4) skip the end operation and call GC. SuppressFinalize (this.

 

18. Partition value type and reference type

1. In general, most of the data we create is the reference type.

2. There are four conditions for determining the creation value type.

(1) The primary responsibility of this type is data storage;

(2) are all public interfaces of this type defined by the access data member attributes?

(3) Are you sure this type will never have a derived type?

(4) Are you sure this type never requires polymorphism support?

3. Use the value type to indicate the type of the underlying stored data, and use the reference type to encapsulate program behavior.

4. If you are not sure about the future use of the type, select the reference type.

 

19. Ensure that 0 is a valid state of the value type.

1. The default initialization process of the. NET system sets all objects to 0. We recommend that you use 0 as the default value of the enumeration type.

2. enumeration (enum) must set 0 to a valid choice for enumeration values. All enumerated values are derived from System. ValueType. The default value of enumeration starts with 0.

3. Make sure that 0 is a valid option when creating a custom enumeration value. If you define a flag, you can define 0 as not selecting any flag.

    enum Week    {        None = 0,        Monday = 1,        Tuesday = 2,        Wednesday = 3,        Thursday = 4,        Friday = 5,        Saturday = 6,        Sunday = 7    }

 

20. ensure the constant and atomicity of value types

1. Constant: The value remains unchanged after being created. Because you cannot change the internal status, you can save a lot of unnecessary error checks. It is thread-safe and can be safely exposed to the outside world, because the caller cannot change the internal status of the object.

2. When designing a constant type, make sure that no vulnerability exists and the internal status is changed. Because the value type cannot be derived, you do not have to worry about being affected by the derived class.

However, if the constant contains a variable reference type field, we should make defensive copies of these variable types.

Class MyClass {private readonly object [] _ objs; public MyClass (ICollection <object> objs) {_ objs = new object [objs. count]; objs. copyTo (_ objs, 0); // copy} public IEnumerable <object> Objs => _ objs ;}

 

        static void Main(string[] args)        {            var objs = new object[10];            var myClass = new MyClass(objs);            objs[1] = "hi";            Console.WriteLine(myClass.Objs.ToArray()[1]);            Console.Read();        }

Because the array is a reference type, if you do not use CopyTo to copy a copy, the external objs modification will directly affect _ objs in MyClass, because they all point to the same reference.

2. Do not blindly add {get; set;} to each attribute ;}.

 

 

[Blogger] Anti-Bot

Http://www.cnblogs.com/liqingwen/p/6761409.html.

 

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.