首页 > 开发 > 综合 > 正文

C# 编码规范

2024-07-21 02:19:33
字体:
来源:转载
供稿:网友
菜鸟学堂:
technotes, howto series
c# coding style guide
version 0.3
by mike krüger icsharpcode.net



about the c# coding style guide
file organization
indentation
comments
declarations
statements
white space
naming conventions
programming practices
code examples
1. about the c# coding style guide
this document may be read as a guide to writing robust and reliable programs. it focuses on programs written in c#, but many of the rules and principles are useful even if you write in another programming language.

2. file organization
2.1 c# sourcefiles
keep your classes/files short, don't exceed 2000 loc, divide your code up, make structures clearer. put every class in a separate file and name the file like the class name (with .cs as extension of course). this convention makes things much easier.

2.2 directory layout
create a directory for every namespace. (for myproject.testsuite.testtier use myproject/testsuite/testtier as the path, do not use the namespace name with dots.) this makes it easier to map namespaces to the directory layout.

3. indentation
3.1 wrapping lines
when an expression will not fit on a single line, break it up according to these general principles:

break after a comma.
break after an operator.
prefer higher-level breaks to lower-level breaks.
align the new line with the beginning of the expression at the same level on the previous line
example of breaking up method calls:

longmethodcall(expr1, expr2,
expr3, expr4, expr5);
examples of breaking an arithmetic expression:


prefer:

var = a * b / (c - g + f) +
4 * z;

bad style – avoid:

var = a * b / (c - g +
f) + 4 * z;
the first is preferred, since the break occurs outside the paranthesized expression (higher level rule). note that you indent with tabs to the indentation level and then with spaces to the breaking position in our example this would be:

> var = a * b / (c - g + f) + > ......4 * z;
where '>' are tab chars and '.' are spaces. (the spaces after the tab char are the indent with of the tab). a good coding practice is to make the tab and space chars visible in the editor which is used.

3.2 white spaces
an indentation standard using spaces never was achieved. some people like 2 spaces, some prefer 4 and others die for 8, or even more spaces. better use tabs. tab characters have some advantages:

everyone can set their own preferred indentation level
it is only 1 character and not 2, 4, 8 … therefore it will reduce typing (even with smartindenting you have to set the indentation manually sometimes, or take it back or whatever)
if you want to increase the indentation (or decrease), mark one block and increase the indent level with tab with shift-tab you decrease the indentation. this is true for almost any texteditor.
here, we define the tab as the standard indentation character.

don't use spaces for indentation - use tabs!
4. comments
4.1 block comments
block comments should usually be avoided. for descriptions use of the /// comments to give c# standard descriptions is recommended. when you wish to use block comments you should use the following style :

/* line 1 * line 2 * line 3 */
as this will set off the block visually from code for the (human) reader. alternatively you might use this oldfashioned c style for single line comments, even though it is not recommended. in case you use this style, a line break should follow the comment, as it is hard to see code preceeded by comments in the same line:

/* blah blah blah */
block comments may be useful in rare cases, refer to the technote 'the fine art of commenting' for an example. generally block comments are useful for comment out large sections of code.

4.2 single line comments
you should use the // comment style to "comment out" code (sharpdevelop has a key for it, alt+/) . it may be used for commenting sections of code too.

single line comments must be indented to the indent level when they are used for code documentation. commented out code should be commented out in the first line to enhance the visibility of commented out code.

a rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.

4.3 documentation comments
in the .net framework, microsoft has introduced a documentation generation system based on xml comments. these comments are formally single line c# comments containing xml tags. they follow this pattern for single line comments:

/// <summary> /// this class... /// </summary>
multiline xml comments follow this pattern:

/// <exception cref=”bogusexception”> /// this exception gets thrown as soon as a /// bogus flag gets set. /// </exception>
all lines must be preceded by three slashes to be accepted as xml comment lines. tags fall into two categories:

documentation items
formatting/ referencing
the first category contains tags like <summary>, <param> or <exception>. these represent items that represent the elements of a program's api which must be documented for the program to be useful to other programmers. these tags usually have attributes such as name or cref as demonstrated in the multiline example above. these attributes are checked by the compiler, so they should be valid. the latter category governs the layout of the documentation, using tags such as <code>, <list> or <para>.
documentation can then be generated using the 'documentation' item in the #develop 'build' menu. the documentation generated is in htmlhelp format.
for a fuller explanation of xml comments see the microsoft .net framework sdk documentation. for information on commenting best practice and further issues related to commenting, see the technote 'the fine art of commenting'.

5. declarations
5.1 number of declarations per line
one declaration per line is recommended since it encourages commenting1. in other words,

int level; // indentation level int size; // size of table
do not put more than one variable or variables of different types on the same line when declaring them. example:

int a, b; //what is 'a'? what does 'b' stand for?
the above example also demonstrates the drawbacks of non-obvious variable names. be clear when naming variables.

5.2 initialization
try to initialize local variables as soon as they are declared. for example:
string name = myobject.name;
or
int val = time.hours;
note: if you initialize a dialog try to use the using statement:
using (openfiledialog openfiledialog = new openfiledialog()) { ... }
5.3 class and interface declarations
when coding c# classes and interfaces, the following formatting rules should be followed:

no space between a method name and the parenthesis " (" starting its parameter list.
the opening brace "{" appears in the next line after the declaration statement
the closing brace "}" starts a line by itself indented to match its corresponding opening brace.
for example:

class mysample : myclass, imyinterface { int myint; public mysample(int myint) { this.myint = myint ; } void inc() { ++myint; } void emptymethod() { } }
for a brace placement example look at section 10.1.

6. statements
6.1 simple statements
each line should contain only one statement.

6.2 return statements
a return statement should not use outer most parentheses. don't use :

return (n * (n + 1) / 2); use : return n * (n + 1) / 2;
6.3 if, if-else, if else-if else statements
if, if-else and if else-if else statements should look like this:

if (condition) { dosomething(); ... } if (condition) { dosomething(); ... } else { dosomethingother(); ... } if (condition) { dosomething(); ... } else if (condition) { dosomethingother(); ... } else { dosomethingotheragain(); ... }
6.4 for / foreach statements
a for statement shoud have following form :
for (int i = 0; i < 5; ++i) { ... }
or single lined (consider using a while statement instead) :
for (initialization; condition; update) ; a foreach should look like : foreach (int i in intlist) { ... }
note: generally use brackets even if there is only one statement in the loop.
6.5 while/do-while statements
a while statement should be written as follows:
while (condition) { ... }
an empty while should have the following form:

while (condition) ;
a do-while statement should have the following form:
do { ... } while (condition);
6.6 switch statements
a switch statement should be of following form:
switch (condition) { case a: ... break; case b: ... break; default: ... break; }
6.7 try-catch statements
a try-catch statement should follow this form:

try { ... } catch (exception) {} or try { ... } catch (exception e) { ... } or try { ... } catch (exception e) { ... } finally { ... }
7. white space
7.1 blank lines
blank lines improve readability. they set off blocks of code which are in themselves logically related. two blank lines should always be used between:

logical sections of a source file
class and interface definitions (try one class/interface per file to prevent this case) one blank line should always be used between:
methods
properties
local variables in a method and its first statement
logical sections inside a method to improve readability note that blank lines must be indented as they would contain a statement this makes insertion in these lines much easier.
7.2 inter-term spacing
there should be a single space after a comma or a semicolon, for example:
testmethod(a, b, c); don't use : testmethod(a,b,c)
or
testmethod( a, b, c ); single spaces surround operators (except unary operators like increment or logical not), example: a = b; // don't use a=b; for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i) // or // for(int i=0;i<10;++i)
7.3 table like formatting
a logical block of lines should be formatted as a table:

string name = "mr. ed"; int myvalue = 5; test atest = test.testyou;
use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels.

8. naming conventions
8.1 capitalization styles
8.1.1 pascal casing
this convention capitalizes the first character of each word (as in testcounter).

8.1.2 camel casing
this convention capitalizes the first character of each word except the first one. e.g. testcounter.

8.1.3 upper case
only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use pascal casing instead. for example:

public class math { public const pi = ... public const e = ... public const feigenbaumnumber = ... }
8.2. naming guidelines
generally the use of underscore characters inside names and naming according to the guidelines for hungarian notation are considered bad practice.

hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. this style of naming was widely used in early windows programming, but now is obsolete or at least should be considered deprecated. using hungarian notation is not allowed if you follow this guide.

and remember: a good variable name describes the semantic not the type.

an exception to this rule is gui code. all fields and variable names that contain gui elements like button should be postfixed with their type name without abbreviations. for example:

system.windows.forms.button cancelbutton; system.windows.forms.textbox nametextbox;
8.2.1 class naming guidelines
class names must be nouns or noun phrases.
usepascal casing see 8.1.1
do not use any class prefix
8.2.2 interface naming guidelines
name interfaces with nouns or noun phrases or adjectives describing behavior. (example icomponent or ienumberable)
use pascal casing (see 8.1.1)
use i as prefix for the name, it is followed by a capital letter (first char of the interface name)
8.2.3 enum naming guidelines
use pascal casing for enum value names and enum type names
don’t prefix (or suffix) a enum type or enum values
use singular names for enums
use plural name for bit fields.
8.2.4 readonly and const field names
name static fields with nouns, noun phrases or abbreviations for nouns
use pascal casing (see 8.1.1)
8.2.5 parameter/non const field names
do use descriptive names, which should be enough to determine the variable meaning and it’s type. but prefer a name that’s based on the parameter’s meaning.
use camel casing (see 8.1.2)
8.2.6 variable names
counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops. (see 10.2 for an example on more intelligent naming for global counters etc.)
use camel casing (see 8.1.2)
8.2.7 method names
name methods with verbs or verb phrases.
use pascal casing (see 8.1.2)
8.2.8 property names
name properties using nouns or noun phrases
use pascal casing (see 8.1.2)
consider naming a property with the same name as it’s type
8.2.9 event names
name event handlers with the eventhandler suffix.
use two parameters named sender and e
use pascal casing (see 8.1.1)
name event argument classes with the eventargs suffix.
name event names that have a concept of pre and post using the present and past tense.
consider naming events using a verb.
8.2.10 capitalization summary
type case notes
class / struct pascal casing
interface pascal casing starts with i
enum values pascal casing
enum type pascal casing
events pascal casing
exception class pascal casing end with exception
public fields pascal casing
methods pascal casing
namespace pascal casing
property pascal casing
protected/private fields camel casing
parameters camel casing

9. programming practices
9.1 visibility
do not make any instance or class variable public, make them private. for private members prefer not using “private” as modifier just do write nothing. private is the default case and every c# programmer should be aware of it.

use properties instead. you may use public static fields (or const) as an exception to this rule, but it should not be the rule.

9.2 no 'magic' numbers
don’t use magic numbers, i.e. place constant numerical values directly into the source code. replacing these later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded into your code in 50 lines scattered troughout your 25000 loc) is error-prone and unproductive. instead declare a const variable which contains the number :

public class mymath { public const double pi = 3.14159... }
10. code examples
10.1 brace placement example
namespace showmethebracket { public enum test { testme, testyou } public class testmeclass { test test; public test test { get { return test; } set { test = value; } } void dosomething() { if (test == test.testme) { //...stuff gets done } else { //...other stuff gets done } } } }
brackets should begin on a new line only after:
namespace declarations (note that this isnew in version 0.3 and was different in 0.2)
class/ interface / struct declarations
method declarations
10.2 variable naming example
instead of :
for (int i = 1; i < num; ++i) { meetscriteria[i] = true; } for (int i = 2; i < num / 2; ++i) { int j = i + i; while (j <= num) { meetscriteria[j] = false; j += i; } } for (int i = 0; i < num; ++i) { if (meetscriteria[i]) { console.writeline(i + " meets criteria"); } } try intelligent naming : for (int primecandidate = 1; primecandidate < num; ++primecandidate) { isprime[primecandidate] = true; } for (int factor = 2; factor < num / 2; ++factor) { int factorablenumber = factor + factor; while (factorablenumber <= num) { isprime[factorablenumber] = false; factorablenumber += factor; } } for (int primecandidate = 0; primecandidate < num; ++primecandidate) { if (isprime[primecandidate]) { console.writeline(primecandidate + " is prime."); } }
note: indexer variables generally should be called i, j, k etc. but in cases like this, it may make sense to reconsider this rule. in general, when the same counters or indexers are reused, give them meaningful names.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表