[. NET] textbook C # (2)-. NET resource hosting,
Effective C # (2)-. NET resource hosting
Introduction
Continue Objective C # Reading Notes (1)-C # language habits.
In. NET, GC will help us manage the memory. We don't need to worry about memory leakage, resource allocation, pointer initialization, and other issues. However, it is not omnipotent, because the unmanaged resources need to be cleaned by ourselves, such as file handles, database connections, GDI + objects, and COM objects.
Directory
- 12. We recommend that you use the member initializer instead of the value assignment statement.
- 13. initialize static member variables correctly
- Iv. Minimize repeated initialization Logic
- 15. Use using and try/finally to clear Resources
- 16. Avoid creating unnecessary objects
- VII. Implementation of standard destruction Models
- 18. Partition value type and reference type
- 19. Ensure that 0 is a valid state of the value type.
- 20. ensure the constant and atomicity of value types
12. We recommend that you use the member initializer instead of the value assignment statement.
1. In the following three cases, do not use 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. before using the initialization syntax, all constructors set the variable to the same value.
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 are executed and before variables or familiarity are accessed for the first time. You can use this function to initialize static variables, implement Singleton mode, or perform any operations required before the execution class is available.
2. Static initializes and static constructors are the best choice for static members of the initialization class.
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.
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.
16. Avoid creating unnecessary objects
1. GC can manage the memory well, but no matter how funny 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. Another Font object will be created for each call, and its content is exactly the same as before. GC cleans up the garbage for you every time, which is obviously very inefficient.
Upgrade myFont to a static variable.
Private readonly Font _ myFont = new Font ("Arial", 10.0f); public void Paint () {Console. WriteLine ($ "use {_ myFont} for painting ");}
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.
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. Are you sure you want to create a condition for the 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 many necessary error checks, which are 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.