C# Coding Conventions(译)
Implicitly Typed Local Variables 隐式类型的局部变量
Unsigned Data Type 无符号类型
Arrays 数组
Delegates 委托
try-catch and using Statements in Exception Handling 异常处理中的 try-catch 和 using 语句
&& and || Operators
New Operator New 运算符
Event Handling 事件处理
Static Members 静态成员
LINQ Queries LINQ查询
C# Coding Conventions C#编码规范
The C# Language Specification does not define a coding standard. However, the guidelines in this topic are used by Microsoft to develop samples and documentation.
C#语言规范不是用来规定编码标准。然而,这些规范都是微软在开发示例和文档时遵循的。
Coding conventions serve the following purposes:
编码规范是为了达成下列目标:
They create a consistent look to the code, so that readers can focus on content, not layout.
保证代码外观的一致性,让读者讲精力集中在内容上,而不是形式。
They enable readers to understand the code more quickly by making assumptions based on previous experience.
通过良好的命名规范,使读者可以结合过往经验快速理解代码。
They facilitate copying, changing, and maintaining the code.
通过规范简化复制、更改和维护代码。
They demonstrate C# best practices.
演示C#最佳实践。
Naming Conventions 命名规范
- In short examples that do not include using directives, use namespace qualifications. If you know that a namespace is imported by default in a project, you do not have to fully qualify the names from that namespace. Qualified names can be broken after a dot (.) if they are too long for a single line, as shown in the following example.
在不包括using指令的短示例中,使用命名空间限定。如果你知道命名空间默认导入项目中,则不必完全限定来自该命名空间的名称。 如果命名空间限定名太长,则可以在点 (.) 后中断限定名称,如下例所示。
var currentPerformanceCounterCategory =newSystem.Diagnostics.
PerformanceCounterCategory();
- You do not have to change the names of objects that were created by using the Visual Studio designer tools to make them fit other guidelines.
你不必通过更改 Visual Studio 设计器工具创建的对象的名称以使它们适合其他准则。
Layout Conventions 布局规范
Good layout uses formatting to emphasize the structure of your code and to make the code easier to read. Microsoft examples and samples conform to the following conventions:
好的代码布局用格式来强调代码的结构并使代码易于阅读。 Microsoft 示例和样本遵循以下规范:
Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). For more information, see Options, Text Editor, C#, Formatting.
使用默认的代码编辑器设置(智能缩进、4 字符缩进、制表符保存为空格)。
Write only one statement per line.
每行只写一条语句。
Write only one declaration per line.
每行只写一个声明。
If continuation lines are not indented automatically, indent them one tab stop (four spaces).
如果连续行未自动缩进,则缩进一个tab的宽度(4空格)。
Add at least one blank line between method definitions and property definitions.
每个方法定义和每个属性定义间至少间隔一个空白行。
Use parentheses to make clauses in an expression apparent, as shown in the following code.
使用()号让语句更清晰明了,如下代码所示。
if((val1 > val2)&&(val1 > val3))
{
// Take appropriate action.
}
Commenting Conventions 注释规范
Place the comment on a separate line, not at the end of a line of code.
将注释放在单独的行上,而非代码行的末尾。
Begin comment text with an uppercase letter.
注释以大写字母开头。
End comment text with a period.
注释以句号结尾。
Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.
注释分隔符
//
与注释文本间空一个空格,如下例所示。
// The following declaration creates a query. It does not run
// the query.
- Do not create formatted blocks of asterisks around comments.
不要在注释周围创建格式化的星号块。
Language Guidelines 语言准则
The following sections describe practices that the C# team follows to prepare code examples and samples.
以下各节介绍 C# 团队编写示例和样本时遵循的做法。
String Data Type String数据类型
- Use the
+
operator to concatenate short strings, as shown in the following code.使用“+”运算符来连接短字符串,如下代码所示。
string displayName = nameList[n].LastName+", "+ nameList[n].FirstName;
- To append strings in loops, especially when you are working with large amounts of text, use a StringBuilder object.
在循环中拼接字符串,尤其是有大量字符串时,请使用StringBuilder对象。
var phrase ="lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
var manyPhrases =newStringBuilder();
for(var i =0; i <10000; i++)
{
manyPhrases.Append(phrase);
}
//Console.WriteLine("tra" + manyPhrases);
Implicitly Typed Local Variables 隐式类型的局部变量
- Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.
当变量类型明显来自赋值的右侧时,或者当具体类型不重要时,请对本地变量进行隐式类型化。
// When the type of a variable is clear from the context, use var
// in the declaration.
var var1 ="This is clearly a string.";
var var2 =27;
var var3 =Convert.ToInt32(Console.ReadLine());
- Do not use var when the type is not apparent from the right side of the assignment.
当变量并非明显来自赋值右侧时,请勿使用var。
// When the type of a variable is not clear from the context, use an
// explicit type.
int var4 =ExampleClass.ResultSoFar();
- Do not rely on the variable name to specify the type of the variable. It might not be correct.
不用依靠变量名来判断变量类型。这可能是错误的。
// Naming the following variable inputInt is misleading.
// It is a string.
var inputInt =Console.ReadLine();
Console.WriteLine(inputInt);
Avoid the use of
var
in place of dynamic.避免用
var
来代替dynamic
。Use implicit typing to determine the type of the loop variable in for and foreach loops.
for和foreach循环中推荐使用var。
The following example uses implicit typing in a for
statement.
下例for循环中使用隐式类型化。
var syllable ="ha";
var laugh ="";
for(var i =0; i <10; i++)
{
laugh += syllable;
Console.WriteLine(laugh);
}
The following example uses implicit typing in a foreach
statement.
下例foreach循环中使用隐式类型化。
foreach(var ch in laugh)
{
if(ch =='h')
Console.Write("H");
else
Console.Write(ch);
}
Console.WriteLine();
Unsigned Data Type 无符号类型
- In general, use
int
rather than unsigned types. The use ofint
is common throughout C#, and it is easier to interact with other libraries when you useint
.通常,使用 int 而不是无符号类型。 int 的使用在整个 C# 中都很常见,并且当你使用 int 时,更易于与其他库交互。
Arrays 数组
- Use the concise syntax when you initialize arrays on the declaration line.
使用简洁的语法来声明数组。
// Preferred syntax. Note that you cannot use var here instead of string[].
string[] vowels1 ={"a","e","i","o","u"};
// If you use explicit instantiation, you can use var.
var vowels2 =new string[]{"a","e","i","o","u"};
// If you specify an array size, you must initialize the elements one at a time.
var vowels3 =new string[5];
vowels3[0]="a";
vowels3[1]="e";
// And so on.
Delegates 委托
- Use the concise syntax to create instances of a delegate type.
使用简洁的语法来创建委托实例。
// First, in class Program, define the delegate type and a method that
// has a matching signature.
// Define the type.
public delegate void Del(string message);
// Define a method that has a matching signature.
public static void DelMethod(string str)
{
Console.WriteLine("DelMethod argument: {0}", str);
}
// In the Main method, create an instance of Del.
// Preferred: Create an instance of Del by using condensed syntax.
Del exampleDel2 =DelMethod;
// The following declaration uses the full syntax.
Del exampleDel1 =new Del(DelMethod);
try-catch and using Statements in Exception Handling 异常处理中的 try-catch 和 using 语句
- Use a try-catch statement for most exception handling.
对大多数异常处理使用 try-catch 语句。
staticstringGetValueFromArray(string[] array,int index)
{
try
{
return array[index];
}
catch(System.IndexOutOfRangeException ex)
{
Console.WriteLine("Index is out of range: {0}", index);
throw;
}
}
- Simplify your code by using the C# using statement. If you have a try-finally statement in which the only code in the
finally
block is a call to theDispose method, use ausing
statement instead.如果你异常处理 finally 块中的唯一代码是调用 Dispose 方法,请改用 using。
// This try-finally statement only calls Dispose in the finally block.
Font font1 =newFont("Arial",10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if(font1 !=null)
{
((IDisposable)font1).Dispose();
}
}
// You can do the same thing with a using statement.
using(Font font2 =newFont("Arial",10.0f))
{
byte charset = font2.GdiCharSet;
}
&& and || Operators
- To avoid exceptions and increase performance by skipping unnecessary comparisons, use && instead of & and || instead of | when you perform comparisons, as shown in the following example.
若要通过跳过不必要的比较来避免异常或提高性能,请在执行比较时使用 && 来代替 &,使用 || 来代替 | ,如下例所示。
Console.Write("Enter a dividend: ");
var dividend =Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a divisor: ");
var divisor =Convert.ToInt32(Console.ReadLine());
// If the divisor is 0, the second clause in the following condition
// causes a run-time error. The && operator short circuits when the
// first expression is false. That is, it does not evaluate the
// second expression. The & operator evaluates both, and causes
// a run-time error when divisor is 0.
if((divisor !=0)&&(dividend / divisor >0))
{
Console.WriteLine("Quotient: {0}", dividend / divisor);
}
else
{
Console.WriteLine("Attempted division by 0 ends up here.");
}
New Operator New 运算符
- Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.
使用简洁的形式来实例化隐式类型,如下声明所示。
var instance1 =newExampleClass();
The previous line is equivalent to the following declaration.
上一行等同于下面的声明。
ExampleClass instance2 =newExampleClass();
- Use object initializers to simplify object creation.
使用对象初始化器简化对象的创建。
// Object initializer.
var instance3 =newExampleClass{Name="Desktop", ID =37414,
Location="Redmond",Age=2.3};
// Default constructor and assignment statements.
var instance4 =newExampleClass();
instance4.Name="Desktop";
instance4.ID =37414;
instance4.Location="Redmond";
instance4.Age=2.3;
Event Handling 事件处理
- If you are defining an event handler that you do not need to remove later, use a lambda expression.
如果你正在定义一个你稍后不会删除的事件处理程序,请使用Lambda表达式。
publicForm2()
{
// You can use a lambda expression to define an event handler.
this.Click+=(s, e)=>
{
MessageBox.Show(
((MouseEventArgs)e).Location.ToString());
};
}
// Using a lambda expression shortens the following traditional definition.
publicForm1()
{
this.Click+=newEventHandler(Form1_Click);
}
voidForm1_Click(object sender,EventArgs e)
{
MessageBox.Show(((MouseEventArgs)e).Location.ToString());
}
Static Members 静态成员
- Call static members by using the class name: ClassName.StaticMember. This practice makes code more readable by making static access clear. Do not qualify a static member defined in a base class with the name of a derived class. While that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.
使用类名来调用静态成员;类名.静态成员名。这种做法通过指明静态访问使代码更易读。请勿使用派生类名来限定基类中定义的静态成员。当那样的代码编译时,代码的可读性会造成误导,若将来你在派生类添加了同名的静态成员,代码可能会崩溃。
LINQ Queries LINQ查询
- Use meaningful names for query variables. The following example uses
seattleCustomers
for customers who are located in Seattle.查询变量使用有意义的名称。下面示例中使用
seattleCustomers
来表示住在Seattle(西雅图)的客户。
var seattleCustomers =
from cust in customers
where cust.City=="Seattle"
select cust.Name;
- Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.
使用别名来确保匿名类型的属性名都是Pascal命名法。
- Pascal(帕斯卡): 所有单词首字母大写。例如 WriteLine
- Camel(驼峰式): 第一个单词首字母小写,其他单词首字母大写。例如 secondField
var localDistributors =
from customer in customers
join distributor in distributors on customer.City equals distributor.City
select new{Customer= customer,Distributor= distributor };
- Rename properties when the property names in the result would be ambiguous. For example, if your query returns a customer name and a distributor ID, instead of leaving them as
Name
andID
in the result, rename them to clarify thatName
is the name of a customer, andID
is the ID of a distributor.如果结果中的属性名模棱两可,则对其重命名。例如,如果你的查询返回了客户名称和分销商ID,在返回结果不要将它们存为
Name
和ID
,而是应该重命名以明确Name
指的是客户的名称,ID
指的是分销商的ID。
var localDistributors2 =
from cust in customers
join dist in distributors on cust.City equals dist.City
select new{CustomerName= cust.Name,DistributorID= dist.ID };
- Use implicit typing in the declaration of query variables and range variables.
声明查询变量和范围变量时使用隐式类型。
var seattleCustomers =
from cust in customers
where cust.City=="Seattle"
select cust.Name;
Align query clauses under the from clause, as shown in the previous examples.
对其查询语句和from子句,如上面的几个例子所示。
Use where clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.
在别的查询语句之前使用where子句,来确保后面查询的是筛选后的数据集。
var seattleCustomers2 =
from cust in customers
where cust.City=="Seattle"
orderby cust.Name
select cust;
- Use multiple
from
clauses instead of a join clause to access inner collections. For example, a collection ofStudent
objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received the score.使用多行
from
子句来代替Join子句访问内部集合。例如,一个Student
集合里,可能每个学生都有一个考试分数集合。当执行下面的查询时,它将返回90分以上的成绩,并返回得到该分数的学生的姓氏。
// Use a compound from to access the inner sequence within each element.
var scoreQuery =
from student in students
from score in student.Scores
where score >90
select new{Last= student.LastName, score };
Security 安全性
Follow the guidelines in Secure Coding Guidelines.
请遵循代码安全维护指南中的准则。
C# Coding Conventions(译)的更多相关文章
- JavaScript Patterns 2.9 Coding Conventions
It’s important to establish and follow coding conventions—they make your code consistent, predictabl ...
- C# Coding Conventions, Coding Standards & Best Practices
C# Coding Conventions, Coding Standards & Best Practices Cui, Chikun Overview Introduction This ...
- Kotlin Reference (三) Coding Conventions
most from reference 命名规则 1.使用驼峰式命名规则,尽量避免在命名中使用下划线 2.类型以大写字母开头 3.方法和属性以小写字母开头 4.使用4个空格缩进 5.public的方法 ...
- C# Coding & Naming Conventions
Reference document https://msdn.microsoft.com/en-us/library/ff926074.aspx https://msdn.microsoft.com ...
- [译]Vulkan教程(02)概况
[译]Vulkan教程(02)概况 这是我翻译(https://vulkan-tutorial.com)上的Vulkan教程的第2篇. This chapter will start off with ...
- 【译】Android API 规范
[译]Android API 规范 译者按: 修改R代码遇到Lint tool的报错,搜到了这篇文档,aosp仓库地址:Android API Guidelines. 58e9b5f Project ...
- Some practices to write better C#/.NET code(译)
C#(.NET)中有关编码的一些建议,原文地址:http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Cs ...
- [译]JavaScript:将字符串两边的双引号转换成单引号
原文:http://ariya.ofilabs.com/2012/02/from-double-quotes-to-single-quotes.html 代码的不一致性总是让人发狂,如果每位开发者都能 ...
- Code Conventions for the JavaScript Programming Language
This is a set of coding conventions and rules for use in JavaScript programming. It is inspired by t ...
随机推荐
- http协议重点
https://www.cnblogs.com/ranyonsue/p/5984001.html HTTP简介 HTTP协议是Hyper Text Transfer Protocol(超文本传输协议) ...
- pyhton:图像旋转
最近一个作业中要用到图像旋转,分享一下学习过程.如有讲错的地方,恳请指正! 图像旋转,想想真简单啊,不就是将图像矩阵乘上一个旋转平移矩阵就完了吗?实际上还真没这么简单.首先这个旋转平移矩阵怎么获得?通 ...
- 04-PHP-redis
[Redis] 先安装tcl: yum install tcl [下载和安装] 官网http://redis.io/ 下载最新的稳定版本,这里是3.2.0, 然后解压文件并进入. $ sudo ...
- javascript函数大全
JavaScript函数大全 1.document.write(""); 输出语句2.JS中的注释为//3.传统的HTML文档顺序是:document->html->( ...
- eclipse 使 用Ctrl+鼠标左键进入mapper.xml文件的方法
在 >eclipse MarketPlace中下载>Mybatipse 插件安装重启即可完成
- Selenium常用方法及函数、txt参数化
常用方法及函数: 1.表单的提交方法:submit解释:查找到表单(from)直接调用submit即可实例:driver.find_element_by_id("form1").s ...
- Navi.Soft31.任务管理器(定时同步+数据采集)
1系统简介 1.1功能简述 在众多的软件分类中,有几类的软件不是很重要,但也很重要.它们有的是每隔一段时间需要执行一些任务的软件,我们叫它定时类软件:还有一种软件是采集网页中的数据,我们叫它采集类软件 ...
- .NET平台开源项目速览(19)Power BI神器DAX Studio
PowerBI更新频繁,已经有点更不上的节奏,一直在关注和学习中,基本的一些操作大概是没问题,更重要的是注重Power Query,M函数,以及DAX的使用,这才是核心. 上个月研究了DAX的一些 ...
- Angular4.0用命令行创建组件服务出错
之前使用cnpm创建的angular4.0项目,由于cnpm下载的node_modules资源经常会有部分缺失,所以在用命令行创建模板.服务的时候会报错: Error: ELOOP: too many ...
- hdu 1010 回溯加奇偶性剪枝
普通的剪枝会超时,必须加入奇偶性剪枝. 直接上图: AC代码: #include<cstdio> #include<cstring> #include<algorithm ...