1. 不要使用””, 使用string.Empty
string name = string.Empty;
2. 善于合并if
public bool Equals(CommentData obj) {
if (!CommentId.Equals(obj.CommentId)) return false;
if (!Comment.Equals(obj.Comment)) return false;
if (!CommentorId.Equals(obj.CommentorId)) return false;
return true;
}
--------->>>
public bool Equals(CommentData obj) {
return CommentId == obj.CommentId &&
Comment.Equals(obj.Comment) &&
CommentorId == obj.CommentorId;
}
3. 不断重构你的代码
4. 用 Linq 简化代码
foreach (CommentData data in Comments)
{
if (data.CommentId.HasValue)
throw new ArgumentNullException("Create is only for saving new data. Call save for existing data.", "data");
}
--------------->>>
if (Comments.Any(data => data.CommentId.HasValue))
{
throw new ArgumentNullException("Create is only for saving new data. Call save for existing data.", "data");
}
5. 运用 ?:和??
string name = value; if (value == null) { name = string.Empty; }
------------>>>
string name = (value != null) ? value : string.Empty;
或: string name = value ?? string.Empty;6.运用AS
if (employee is SalariedEmployee) { var salEmp = (SalariedEmployee)employee; pay = salEmp.WeeklySalary; // ... }
----------------------------------->>>7. 运用 using, 去除dispose()var salEmployee = employee as SalariedEmployee; if (salEmployee != null) { pay = salEmployee.WeeklySalary; // ... }
------------------------------->>>public IEnumerable<Order> GetOrders() { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader rs = null; var orders = new List<Order>(); try { con = new SqlConnection("some connection string"); cmd = new SqlCommand("select * from orders", con); rs = cmd.ExecuteReader(); while (rs.Read()) { // ... } } finally { rs.Dispose(); cmd.Dispose(); con.Dispose(); } return orders; }
再次简化:public IEnumerable<Order> GetOrders() { var orders = new List<Order>(); using (var con = new SqlConnection("some connection string")) { using (var cmd = new SqlCommand("select * from orders", con)) { using (var rs = cmd.ExecuteReader()) { while (rs.Read()) { // ... } } } } return orders; }
public IEnumerable<Order> GetOrders() { var orders = new List<Order>(); using (var con = new SqlConnection("some connection string")) using (var cmd = new SqlCommand("select * from orders", con)) using (var rs = cmd.ExecuteReader()) { while (rs.Read()) { // ... } } return orders; }