1。 类型转换的时候,以前都是为了方便直接用try,其实会影响代码执行的效率,今天看到一个很好的方法:
/// <summary>
/// 判断一个数据类型是不是整型
/// </summary>
/// <param name="aa"></param>
/// <returns></returns>
public static bool isnumber(string aa)
{
int value = 0;
bool isnumber = int.TryParse(aa, out value);
return isnumber;
}
2。 在遍历处理大型的数据集的时候,用for循环比用foreach的效率快很多:
for (int count = 0; count < dt.Rows.Count; count++)
{
Console.WriteLine(dt.Rows[count]["title"].ToString());
//数据量大的话效率会快一点
}
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row["title"].ToString());
}
3 使用string.Format构造字符串要比直接使用+号连接好很多,不会产生字符串垃圾副本:
string updateQueryText = string.Format("update table1 set Name='{0}' where Id={1}", name, id);
string updateQueryText = "update table1 set Name='" + name + "' where Id=" + id;
4 在使用函数连接数据库的时候,使用using可以更好的释放资源:
//try的方法
public void DALMethod()
{
SqlConnection connection = null;
try
{
connection = new SqlConnection("**");
connection.Open();
//implement
}
catch (Exception exception)
{
}
finally
{
connection.Close();
connection.Dispose();
}
}
//using的方法
public void DALMethod()
{
using (SqlConnection connection = new SqlConnection("**"))
{
connection.Open();
//implement
}
}