初学C#常见的注意事项

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using System.Collections; namespace 面试题目 { class 初学者注意 { public void notice() { //1.使用string变量 string test = "dinglang"; //判断字符串是否有内容 if (test.Length>0) { } //但是,这个对象很可能为空,所以判断是否为null if (!string.IsNullOrEmpty(test)) { } //2.字符串拼接 //这样做没错。+=实际是调用了String类的Append访问,而且会重新生成新的s对象,影响性能、效率 string s = "a"; s += "b"; s += "c"; s += "d"; //提倡用下面这种方式拼接 StringBuilder sb = new StringBuilder(); sb.Append("a"); sb.Append("b"); sb.Append("c"); sb.Append("d"); //3.使用Console Console.WriteLine("字符串test="+test+"字符串s="+s);//效率更低 Console.WriteLine("字符串test:{0}/ns:{1}",test,s);//使用占位符{},换行符/n 后 效率更高 //4.字符串转换成整型 int i = int.Parse(test);//很可能会抛出异常 i = Convert.ToInt32(test);//如果test为null,会返回0 使用(int)i方式会强制转换 if (int.TryParse(test, out i) ) { //使用TryParse的方式会好点 } //5.调用IDbConnection 的 Close 方法 IDbConnection conn = null; try { conn = new SqlConnection(""); conn.Open(); } finally { conn.Close(); } //调用SqlConnection的构造函数可能会出现一个异常,如果是这样的话,我们还需要调用Close方法吗? try { conn = new SqlConnection(""); conn.Open(); } finally { if (conn != null) { conn.Close(); } } //6.遍历List //public void doSome(List<int> list) //{ //foreach(var item in list) //{ // //item //} //} //如果只遍历List容器中的所有内容的话,那么,使用IEnumerable接口会更好一些。因为函数参数传递一个List对象要比一个IEnumerable接口要花费更多的开销。 //public void doSome(IEnumerable<int> list) //{ //foreach(var item in list) //{ // //item //} //} //7.直接使用数字 if (i == 1) { } else if (i == 2) { } else if (i == 3) { } //为什么不使用枚举呢?注意,要定义在函数外 //public enum Somenums //{ // firstNum = 1, // secondNum = 2, // thirdNum = 3 //} // if (i = Somenums.firstNum) // { // } // else if (Somenums.secondNum) // { // } // else if (Somenums.thirdNum) // { // } //8.字符串替换,截取 string name = "dinglang"; name.Replace("d", "D"); Console.WriteLine(name);//奇怪,明明替换了,怎么打印出来还是“dinglang”啊? name.Substring(0, 4); Console.WriteLine(name);// 奇怪呀!明明截取了,怎么打印出来却还是“dinglang”啊? //哈哈。这是初学者,甚至...经常犯的错。 name =name.Replace("d", "D"); Console.WriteLine(name); name.Substring(0, 4); Console.WriteLine(name); //明白了吧。Replace、Substring等函数,其实是返回一个值,而并不会改变变量name的值。得使用name接收返回值,name的值才会改变。 } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值