I hope to share with you the design ideas and principles of fields and make common progress.
1. Do not rely on the initialization sequence of fields
Class Fielddemo
{
Private Int Id = 1 ; // Obtain the id value through a certain method
Private Classf F1 = New Classf ( 1 ); // Do not rely on other members and execution sequence here
Public Fielddemo ()
{
// Set the dependency and execution sequence in the constructor.
Id = 1 ;
F1 = New Classf (ID );
}
}
Public Class Classf
{
Public Classf ( Int ID)
{
}
}
2. The field should not be public
- Const can be public, but I personally do not recommend using Const.
3. When declaring a field, explicitly assign values instead of relying on the default value
Private IntAge =0;
Private StringName =Null;
PrivateDatetime date = datetime. minvalue;
PublicClassf F =Null;
4. Naming rules: select a noun, noun phrase or adjective + noun
Public Class Classf2
{
Private Int Id = 0 ; // Camel name
Private Static Int Defaultid = 0 ; // Name the instance field Pascal
Private Int M_id = 0 ; // Old naming methods, not recommended or opposed
Private Static Int S_defaultid = 0 ; // Old naming methods, not recommended or opposed
// If it is modifiedCodeConsider naming rules for existing code
}
5. If possible, use the following method to call a field:
- Easy to read and understand
Public Class Classf
{
Private Int Id = 0 ;
Private Static Int Defaultid = 0 ;
Public Classf ( Int ID)
{
// Only test code
Console. writeline (ID ); // Parameters and local variables are not recommended...
Console. writeline ( This . ID ); // Add this to instance fields and members
Console. writeline (classf. defaultid ); // Static Field and member plus class name
}
}
6. If you can, remember to release the Member that has implemented the idisposable interface in dispose.
Public Class Classf3: idisposable
{
Public Filestream newfile = Null ;
Protected Virtual Void Dispose ( Bool Disposing)
{
// True indicates that the code is called by the user and the managed and unmanaged resources are recycled.
// False indicates that the code is called by Clr and only the unmanaged resources are recycled.
If (Disposing)
{
// Release managed resources
Newfile. Close ();
}
// Release unmanaged Resources
}
// Do not provide virtual keywords
// Do not override the implementation of the parent class
Public Void Dispose ()
{
Dispose ( True );
// Because we use dispose to reclaim resources
// Notify GC not to call the terminator to recycle the resource again.
GC. suppressfinalize ( This );
}
}
7. Static readonly and const
- Const has better performance
- If the member must be public, or the member may be directly or indirectly used by a third partyProgramSet Reference. You need to understand that const copies the content to the target location during compilation.
8. Remove unused private fields
Some content is referenced by msdn, fxcop, and other third parties.Article..
I am at a limited level. If you have any omissions or mistakes, please correct them.