- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Text;
- usingSystem.Data.SqlClient;
- usingSystem.Data;
- usingSystem.Collections;
- namespace面试题目
- {
- class初学者注意
- {
- publicvoidnotice()
- {
- //1.使用string变量
- stringtest="dinglang";
- //判断字符串是否有内容
- if(test.Length>0)
- {
- }
- //但是,这个对象很可能为空,所以判断是否为null
- if(!string.IsNullOrEmpty(test))
- {
- }
- //2.字符串拼接
- //这样做没错。+=实际是调用了String类的Append访问,而且会重新生成新的s对象,影响性能、效率
- strings="a";
- s+="b";
- s+="c";
- s+="d";
- //提倡用下面这种方式拼接
- StringBuildersb=newStringBuilder();
- 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.字符串转换成整型
- inti=int.Parse(test);//很可能会抛出异常
- i=Convert.ToInt32(test);//如果test为null,会返回0使用(int)i方式会强制转换
- if(int.TryParse(test,outi))
- {
- //使用TryParse的方式会好点
- }
- //5.调用IDbConnection的Close方法
- IDbConnectionconn=null;
- try{
- conn=newSqlConnection("");
- conn.Open();
- }
- finally{
- conn.Close();
- }
- //调用SqlConnection的构造函数可能会出现一个异常,如果是这样的话,我们还需要调用Close方法吗?
- try{
- conn=newSqlConnection("");
- conn.Open();
- }
- finally{
- if(conn!=null)
- {
- conn.Close();
- }
- }
- //6.遍历List
- //publicvoiddoSome(List<int>list)
- //{
- //foreach(variteminlist)
- //{
- ////item
- //}
- //}
- //如果只遍历List容器中的所有内容的话,那么,使用IEnumerable接口会更好一些。因为函数参数传递一个List对象要比一个IEnumerable接口要花费更多的开销。
- //publicvoiddoSome(IEnumerable<int>list)
- //{
- //foreach(variteminlist)
- //{
- ////item
- //}
- //}
- //7.直接使用数字
- if(i==1)
- {
- }
- elseif(i==2)
- {
- }
- elseif(i==3)
- {
- }
- //为什么不使用枚举呢?注意,要定义在函数外
- //publicenumSomenums
- //{
- //firstNum=1,
- //secondNum=2,
- //thirdNum=3
- //}
- //if(i=Somenums.firstNum)
- //{
- //}
- //elseif(Somenums.secondNum)
- //{
- //}
- //elseif(Somenums.thirdNum)
- //{
- //}
- //8.字符串替换,截取
- stringname="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的值才会改变。
- }
- }
- }
初学C#编程的注意事项
最新推荐文章于 2020-05-21 09:55:14 发布