C # coding specification

xiaoxiao2021-03-06  192

C # Code Specification Posted on 2004-08-01 03:12 Han Feng Taste from: http://www.cnblogs.com/william_fire/articles/29064.aspx1. Avoid placing multiple classes in a file.

2. A file should have only one namespace to avoid placing multiple namespaces in the same file.

3. One file is preferably not more than 500 lines of code (excluding the code generated by the IDE).

4. The length of the code is preferably not more than 25 lines.

5. Avoid more than 5 parameters in the method. If more than exceeded, you should use struct to pass multiple parameters.

6. Do not exceed 80 characters per line code.

7. In principle, try not to manually modify the code generated by the machine.

a) If you need to edit the code generated by the machine (IDE), the editing format and style should comply with the coding standard.

b) Use the piecewise class as much as possible to decompose the partially decomposed into each factor.

Note: The translation of the inspiration is the statement of the source of inspiration. In Visual C # 2005, the syntax of C # has supported Partial modifiers. Its role is to decompose a complete class to each class, compile, compile The machine will be constructed as a class.

Please refer to

http://blog.joycode.com/zhanbos/archive/2004/05/25/22402.aspx

Http://weblogs.asp.net/jaybaz_ms/archive/2004/04/28/122392.aspx

8. Avoid using the annotation interpretation of the code.

a) The code should be self-explanatory. Good code itself should be specific and well-readable, and the variables and methods used are not required to be annotated.

9. Documentation should only be used only for Assumptions, Algorithm Insights, and more.

10. Avoid using the method level document.

a) Use the extended API documentation.

b) The method level comment is only used when the method needs to be used by other developers. (In C # is ////)

11. Do not hardly encode the value of the numbers, always use the constructor to set its value.

12. Only the natural structure can be used directly, such as a week of the day.

13. Differentiated read-only variables and constants, if you want to implement read-only variables, you can use the Readonly modifier directly.

Public Class Myclass

{

Public Readonly Int Number;

Public MyClass (int SomeValue)

{

Number = SomeValue;

}

Public const INT daysinweek = 7;

}

14. Each hypothesis must be checked using an ASSERT

a) Average every 15 rows (Assert)

Using system.diagnostics;

Object getObject ()

{...}

Object obj = getObject ();

Debug.Assert (OBJ! = NULL);

15. Each line of the code should be tested through a white box.

16. Only the abnormality that has been displayed has been thrown.

17. In the throwing abnormality subsept subsepts of the captory statement, it always throws raw abnormalities to maintain the stack assignment of the original errors. Catch (Exception Exception)

{

Messagebox.show;

Throw; // and throw Exception.

}

Note: Similarly, it is not recommended to perform a direct returnction operation in a loop statement. For (int i = 0; i <100; i ) {if (i == 10) {return; // does not recommend mode} 18. Avoiding the return value of the method is an error code. 19. Try to avoid defining a custom anomalous class.

20. When you need to define custom anomalies:

a) Custom exception should be inherited in ApplicationException.

b) Provide custom serialization.

21. Avoid using multiple main methods in a single assembly.

22. Only the necessary operations are published, and others are Internal.

23. Avoid using a friend assembly because it increases the coupling of the program.

24. Avoid writing code from the assembly loaded from the specified location.

25. Make the app set as much as possible for minimization code (EXE customer program). Use the class library to replace the included business logic.

26. Avoid providing an explicit value to the enumeration variable.

/ / Correct method

Public Enum Color, PUBLIC ENUM

{

Red, Green, Blue

}

//avoid

Public Enum Color, PUBLIC ENUM

{

RED = 1, Green = 2, Blue = 3

}

27. Avoid designating special types of enumerated variables.

//avoid

Public Enum Color: Long

{

Red, Green, Blue

}

28. Even if the IF statement has only one sentence, the content of the IF statement is to be launched by brace.

29. Avoid using Trinary conditional operators.

30. Avoid calling a function that returns a BOOL value in a condition statement. Particular variables can be used and these local variables are checked.

Bool ISeverythingok ()

{...}

//avoid

IF (ISeverythingok ())

{...}

// Replacement scheme

Bool OK = ISEVERYTHINGOK ();

IF (ok)

{...}

31. Always use 0-based arrays.

32. The array of explicit initialization reference types in the loop.

Public Class Myclass

{}

Myclass [] array = new myclass [100];

For (int index = 0; index

{

Array [index] = new myclass ();

}

33. Try not to provide members variables for public and protected, using properties instead of them.

34. Avoid using NEW to use Override to replace in inheritance.

35. The method of PUBLIC and PROTECTEDs are always marked into Virtual in classes that are not Sealed.

36. Do not use unsafe code (unsafe code) unless you use the Interop (COM or other DLL) code.

37. Avoid explicit conversions, use the AS operator to conversion of compatible types.

DOG DOG = New Germanshepherd ();

Germanshepherd shepherd = dog as germanshepherd;

IF (Shepherd! = NULL)

{...}

38. When class members include commissioned

a) Copy it into a local variable before calling, to avoid concurrency.

b) Be sure to check if it is NULL before calling the delegation.

Public Class MySource, PUBLIC CLASSOURCE

{

Public Event athandler myevent;

Public void fireEvent ()

{// will be entrusted to a local variable. EventHandler Temp = MyEvent; // Determine if it is empty if (Temp! = Null) {

Temp (this, eventargs.empty);

}

}

}

39. Do not provide public event member variables, replace these variables with event accessors.

Public Class MySource, PUBLIC CLASSOURCE

{

MyDelegate m_someevent;

Public Event MyDelegate Someevent

{

Add

{

m_someevent = value;

}

Remove

{

M_Someevent - = Value;

}

}

}

40. Use an event to help classes to publish the definition of an event.

41. Always use the interface.

42. The method and attributes in classes and interfaces are at least 2: 1 ratio.

43. Avoid only one member in an interface.

44. Try to enable 3-5 members in each interface.

45. Members in the interface should not exceed 20.

a) The actual situation may limit 12

46. ​​Avoid including events in interface members.

47. Avoid replace the interface to avoid using an abstract method.

48. Displays the interface in the class level.

49. Recommended explicit interface implementation.

50. Never assume that a type is compatible with an interface and should prevent querying those interfaces.

Sometype obj1;

Imyinterface obj2;

/ * Assume that there is already the code initializes Obj1, next * /

Obj2 = Obj1 as ImyInterface;

IF (Obj2! = NULL)

{

Obj2.method1 ();

}

Else

{

// Handling error

}

51. A string manifesting to the end user (generally referring to the part in the UI interface) Do not use direct encoding, but should be replaced with resource files.

Note: The purpose of this is to facilitate the localization of the software.

52. Do not write directly to the configuration-based string, such as a connection string.

53. When you need to build a long string, you should consider using StringBuilder not to use String to process.

Note: String Every time you have to create a new instance, it takes up the space and produces greater performance consumption relative to StringBuilder. For too frequent string operations, StringBuilder is a good habit.

54. Avoid providing a method in the structure.

a) It is recommended to use parameterized constructor

b) Optional Operation

55. Always provide a static constructor to static variables.

56. Use the early binding to avoid using the later binding.

Note: Although the later binding is flexible, it is not only the performance of the performance, but more is the logic of complexity and chaos.

57. Using the application's logs and tracking.

58. Do not use a goto statement unless otherwise in an incomplete Switch statement.

Note: In principle, the GOTO statement should not be used unless it is allowed to use it without affecting the complexity of the coding.

59. There is always a DEFAULT clause to display information (Assert) in the switch statement.

INT number = someMethod ();

Switch (Number)

{

Case 1:

Trace.WriteLine ("Case 1:");

Break;

Case 2:

Trace.writeline ("Case 2:");

Break;

DEFAULT:

Debug.assert (false);

Break;

}

60. Do not use the THIS pointer unless otherwise call other constructors in the constructor.

/ / Correctly use this example

Public class myclass {

Public myclass (String Message)

{}

Public myclass (): this ("Hello")

{}

}

61. Unless you want to rewrite a member of the subclass with a name conflict or call the base class constructor, do not use Base to access a member of the base class.

/ / Correctly use base

Public Class Dog

{

Public Dog (String Name)

{}

Virtual public void bar (int!

{}

}

Public Class Germanshepherd: Dog

{

Public Germanshe PHERD (STRING NAME): Base (Name)

{}

Override public void bar (int!)

{

Base .bark (howlong);

}

}

62. To achieve DISPOSE () and Finalize () by template.

63. Usually avoiding the code from system.object to convert and convert by System.Object, and replacing it with a forced conversion or AS operator.

Class SomeClass

{}

//avoid:

Class myclass

{

Void SomeMethod (t t)

{

Object temp = t;

SomeClass Obj = (SomeClass) TEMP;

}

}

/ / Correct:

Class Myclass Where T: SomeClass

{

Void SomeMethod (t t)

{

SomeClass Obj = T;

}

}

64. Do not define an interface with a restriction in general. The limit level of the interface can usually replace with a strong type.

Public Class Customer

{...}

//avoid:

Public Interface IList Where T: Customer

{...}

//correct:

Public interface icustomerlist: IList

{...}

65. The limitation of the specific method in the interface is not determined.

66. Always choose the data structure of using C # built-in (general generics)

转载请注明原文地址:https://www.9cbs.com/read-128913.html

New Post(0)