但是,Microsoft 使用本主题中的这些指南开发示例和文档。
编码约定可实现以下目的:
-
它们创建一致的代码外观,从而使读者可以关注内容而非布局。
-
它们使读者能够根据以前的经验作出假设,从而更加快速地理解代码。
-
有利于复制、更改和维护代码。
-
演示 C# 最佳做法。
以下各部分描述了 C# 团队准备代码示例时遵循的做法。
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); } //Console.WriteLine("tra" + manyPhrases);
隐式类型化局部变量
-
隐式类型 的局部变量。
// 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);
-
dynamic。
-
foreach 循环中确定循环变量的类型。
for 语句中使用了隐式类型。
var syllable = "ha"; var laugh = ""; for (var i = 0; i < 10; i++) { laugh += syllable; Console.WriteLine(laugh); }
foreach 语句中使用了隐式类型。
foreach (var ch in laugh) { if (ch == 'h') Console.Write("H"); else Console.Write(ch); } Console.WriteLine();
无符号数据类型
-
int 时很容易与其他库进行交互。
数组
-
在您初始化声明行上的数组时,请使用简洁的语法。
// 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.publicdelegatevoid Del(string message);
// Define a method that has a matching signature.publicstaticvoid 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; } }
-
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();
上面的行与以下声明等效。
ExampleClass instance2 = 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());
};
}
// Using a lambda expression shortens the following traditional definition.public Form1()
{
this.Click += new EventHandler(Form1_Click);
}
void Form1_Click(object sender, EventArgs e)
{
MessageBox.Show(((MouseEventArgs)e).Location.ToString());
}
静态成员
-
不要从派生类访问在基类中定义的静态成员。
LINQ 查询
-
seattleCustomers 代表地处西雅图的客户。
var seattleCustomers = from cust in customers where cust.City == "Seattle" select cust.Name;
-
使用别名以确保通过 Pascal 大小写格式正确设置匿名类型的属性名称的大小写。
var localDistributors = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { Customer = customer, Distributor = distributor };
-
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 };
-
使用隐式类型来声明查询变量和范围变量。
var seattleCustomers = from cust in customers where cust.City == "Seattle" select cust.Name;
-
from 子句下方,如前面的示例所示。
-
where 子句,以确保对一组经过简化和筛选的数据执行后面的查询子句。
var seattleCustomers2 = from cust in customers where cust.City == "Seattle" orderby cust.Name select cust;
-
在执行下面的查询时,它将返回每一个超过 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 };