参考自 MSDN     https://msdn.microsoft.com/zh-cn/library/ff926074.aspx , 只摘要个人觉得有用部分

命名约定

在不包括 using 指令的短示例中,使用命名空间限定。 如果你知道命名空间默认导入项目中,则不必完全限定来自该命名空间的名称。 如果对于单行来说过长,则可以在点 (.) 后中断限定名称,如下面的示例所示

var currentPerformanceCounterCategory = new System.Diagnostics.
PerformanceCounterCategory();

语言准则

String 数据类型

  • 使用 + 运算符来连接短字符串,如下面的代码所示。

string displayName = nameList[n].LastName + ", " + nameList[n].FirstName;

若要在循环中追加字符串,尤其是在使用大量文本时,请使用 StringBuilder 对象。

  var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
var manyPhrases = new StringBuilder();
for (var i = 0; i < 10000; i++)
{
manyPhrases.Append(phrase);
}

隐式类型的局部变量

当变量类型明显来自赋值的右侧时,或者当精度类型不重要时,请对本地变量进行隐式类型化

            // 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());

当类型并非明显来自赋值的右侧时,请勿使用 var

// When the type of a variable is not clear from the context, use an
// explicit type.
int var4 = ExampleClass.ResultSoFar();

请勿依靠变量名称来指定变量的类型。 它可能不正确。

 // Naming the following variable inputInt is misleading.
// It is a string.
var inputInt = Console.ReadLine();
Console.WriteLine(inputInt);

使用隐式类型化来确定 for 和 foreach 循环中循环变量的类型。

            var syllable = "ha";
var laugh = "";
for (var i = 0; i < 10; i++)
{
laugh += syllable;
Console.WriteLine(laugh);
}
   foreach (var ch in laugh)
{
if (ch == 'h')
Console.Write("H");
else
Console.Write(ch);
}
Console.WriteLine();

数组

当在声明行上初始化数组时,请使用简洁的语法。

         // 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.

委托

使用简洁的语法来创建委托类型的实例。

// 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 和 using 语句

对大多数异常处理使用 try-catch 语句。

 static string GetValueFromArray(string[] array, int index)
{
try
{
return array[index];
}
catch (System.IndexOutOfRangeException ex)
{
Console.WriteLine("Index is out of range: {0}", index);
throw;
}
}

通过使用 C# using 语句简化你的代码。 如果你具有 try-finally 语句(该语句中 finally 块的唯一代码是对 Dispose 方法的调用),请使用 using 语句代替。

  // This try-finally statement only calls Dispose in the finally block.
Font font1 = new Font("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 = new Font("Arial", 10.0f))
{
byte charset = font2.GdiCharSet;
}

&& 和 || 运算符

若要通过跳过必要的比较来避免异常和提高性能,请在执行比较时使用 && 来代替 &,使用 || 来代替 | ,如下面的示例所示。

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 运算符

隐式类型化时,请使用对象实例化的简洁形式,如下面的声明所示。

var instance1 = new ExampleClass();

使用对象初始值设定项来简化对象创建

 // Object initializer.
var instance3 = new ExampleClass { Name = "Desktop", ID = 37414,
Location = "Redmond", Age = 2.3 }; // Default constructor and assignment statements.
var instance4 = new ExampleClass();
instance4.Name = "Desktop";
instance4.ID = 37414;
instance4.Location = "Redmond";
instance4.Age = 2.3;

事件处理

如果你正定义一个稍后不需要删除的事件处理程序,请使用 lambda 表达式。

public Form2()
{
// You can use a lambda expression to define an event handler.
this.Click += (s, e) =>
{
MessageBox.Show(
((MouseEventArgs)e).Location.ToString());
};
}

静态成员

  • 通过使用类名称调用静态成员:ClassName.StaticMember。 这种做法通过明确静态访问使代码更易于阅读。 请勿使用派生类的名称限定基类中定义的静态成员。 编译该代码时,代码可读性具有误导性,如果向派生类添加具有相同名称的静态成员,代码可能会被破坏

LINQ 查询

对查询变量使用有意义的名称。 下面的示例为位于西雅图的客户使用 seattleCustomers

            var seattleCustomers = from cust in customers
where cust.City == "Seattle"
select cust.Name;

在其他查询子句之前使用 where 子句,以确保后面的查询子句作用于经过减少和筛选的数据集。

var seattleCustomers2 = from cust in customers

where cust.City == "Seattle"

orderby cust.Name

select cust;

使用多行 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 };

C# 编码约定的更多相关文章

  1. [译]C#编码约定

    原文:https://msdn.microsoft.com/en-us/library/ff926074.aspx 编码约定的目的是: 创建统一格式的代码,让读者的注意力更集中在内容上面,而不是结构 ...

  2. Dubbo的一些编码约定和设计原则

    编码约定 代码风格 Dubbo 的源代码和 JavaDoc 遵循以下的规范: Code Conventions for the Java Programming Language How to Wri ...

  3. 一些达成共识的JavaScript编码约定[转]

    如果你的代码易于阅读,那么代码中bug也将会很少,因为一些bug可以很容被调试,并且,其他开发者参与你项目时的门槛也会比较低.因此,如果项目中有多人参与,采取一个有共识的编码风格约定非常有必要.与其他 ...

  4. C# 编码约定(C# 编程指南)

    C#注释约定 将注释放到另一行,而不要放在代码行的末尾. 以大写字母作为注释文本的开头. 以句点结束注释文本. 在注释分隔符 (//) 和注释文本之间插入一个空格,如以下示例所示. // The fo ...

  5. Mediawiki.org的PHP编码约定

    http://www.mediawiki.org/wiki/Manual:Coding_conventions/PHP assignment作为expression来用看起来像个错误(looks su ...

  6. 个人c#编码约定 继承C#编码约定

    1.内插字符 串取代  字符串复合格式设置 使用这个写法: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it' ...

  7. C#编码规范 转 http://www.cnblogs.com/wulinfeng/archive/2012/08/31/2664720.html

    C#编码规范   1  规范目的 ……………………………………………………… 3 2  适用范围 ……………………………………………………… 3 3  代码注释 ………………………………………………… ...

  8. Nim编码风格

    介绍 Nim语言不限制开发人员使用哪种具体的编码风格, 但为了社区的发展,在编写一些标准库的时候还是应该遵从统一的编码风格 这篇文章会列出一系列的编码风格准则,供大家参考. 但值得注意的是,有很多例外 ...

  9. c#编码规范

    1  规范目的 --------------------- 3 2  适用范围 --------------------- 3 3  代码注释 --------------------- 3 3.1  ...

随机推荐

  1. .NET设计模式(3):抽象工厂模式(Abstract Factory)

    ):抽象工厂模式(Abstract Factory) 抽象工厂模式(Abstract Factory) --探索设计模式系列之三 Terrylee,2005年12月12日 转载:http://terr ...

  2. 关于local storage 和 session storage以及cookie 区别简析

    session storage 和local storage 都是存储在客户端的浏览器内: 一:关于COOKIE 的缺陷 * Cookie的问题 * 数据存储都是以明文(未加密)方式进行存储 * 安全 ...

  3. Codeforces 390Div2-754D. Fedor and coupons(贪心+优先队列)

    D. Fedor and coupons time limit per test 4 seconds memory limit per test 256 megabytes input standar ...

  4. SVG 矢量图形格式

    SVG(Scalable Vector Graphics)是基于 XML 的一种矢量图形格式,它即可以作为单独的图形文件使用也可以嵌入到网页中并由 JavaScript 来操作,非常方便和灵活.SVG ...

  5. 使用jdbc连接上oracle的两种方法

    1. 使用thin连接 优点:thin驱动都是纯Java代码,并且使用TCP/IP技术通过java的Socket连接上Oracle数据库,所以thin驱动是与平台无关的,无需安装Oracle客户端,只 ...

  6. 剑指OFFER之从1到n中出现1的次数(九度OJ1373)

    题目描述: 亲们!!我们的外国友人YZ这几天总是睡不好,初中奥数里有一个题目一直困扰着他,特此他向JOBDU发来求助信,希望亲们能帮帮他.问题是:求出1~13的整数中1出现的次数,并算出100~130 ...

  7. action 带参数跳转

    都容易忘记 <result name="goOpPolicy" type="redirect">queryPolicy.action?aaaa=${ ...

  8. centos6下安装部署hadoop2.2

    环境准备1.操作系统:centos6.0 64位2.hadoop版本:hahadoop-2.2.0 安装和配置步骤具体如下:1.主机和ip分配如下     ip地址                  ...

  9. 如何避免regionServer宕机

    为什么regionserver 和Zookeeper的session expired? 可能的原因有 1. 网络不好. 2. Java full GC, 这会block所有的线程.如果时间比较长,也会 ...

  10. metasploit(MSF)终端命令大全

    show exploits   列出metasploit框架中的所有渗透攻击模块. show payloads   列出metasploit框架中的所有攻击载荷. show auxiliary   列 ...