using System.Text;
namespace IComparable
{
class readtxt
{
/// <summary>
/// 读取Txt文件
/// </summary>
/// <param name="txtFilePath">Txt文件绝对路径</param>
/// <returns>StringBuilder</returns>
public static StringBuilder ReadTxtFile(string txtFilePath)
{
StringBuilder sb = new StringBuilder();
if (System.IO.File.Exists(txtFilePath))
{
//using自动释放资源
using (System.IO.FileStream FS = new System.IO.FileStream(txtFilePath, System.IO.FileMode.Open))
using (System.IO.StreamReader SR = new System.IO.StreamReader(FS, System.Text.Encoding.Default))
{
string Line = null;
while ((Line = SR.ReadLine()) != null)//最后一个则为空
sb.AppendLine(Line);
}
}
else
{
sb = null;
}
return sb;
}
}
}
由
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;
}
出现using嵌套,影响代码的美观
对其改进:
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;
}
3843

被折叠的 条评论
为什么被折叠?



