您的位置:首页 > 编程语言

写出优雅简明代码理论指导收集

2011-02-16 11:25 387 查看
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. 运用 ?:和??[/code]
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; // ... }
----------------------------------->>>
var salEmployee = employee as SalariedEmployee;
if (salEmployee != null)
{
pay = salEmployee.WeeklySalary;
// ...
}
7. 运用 using, 去除dispose()[/code]

------------------------------->>>

再次简化:
[/code]
[/code][/code]
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: