C#中一些常见的错误和知识点

 using System;
using System.Data;
using System.Data.SqlClient;
public namespace Kehai.Exam.SourceCode   //命名空间不可以有访问修饰符 或 属性
{
    private class Program //命名空间下不能给类添加除 public internal以外的访问修饰符
    {
        public void Main()   //程序入口必须有 static 修饰,且 必须在返回值之前
        {
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection("连接字符串略");  //未打开连接
                SqlCommand command = new SqlCommand(
                    "SELECT name FROM sysdatabases",
                    connection);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.HasRows)
                {
                    string name = reader["name"];  //reader 返回的是Object类型要转换
                    Console.WriteLine(name); 
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if(reader != null)    //超出了reader 的作用域
                    reader.Close();  //超出了reader 的作用域

                if (connection != null)  //超出了connection 的作用域
                    connection.Close();  //超出了connection 的作用域
            }
        }
    }
}


ArrayList arrayList = new ArrayList();
            arrayList.Add(1);
            arrayList.Add(2);
            arrayList.Add(3);
            arrayList.Add(4);
            arrayList.Add(5);
          //删除对象时,索引从 0 开始
            arrayList.RemoveAt(3);     //每次删除一个,arraryList就重新排序, 索引值就会发生
            arrayList.RemoveAt(4);     //改变。可能会发生,索引越界的错误!
            arrayList.RemoveAt(5);


ArrayList和List<T>都提供了Remove方法
Remove方法使用对象的Equals方法确定匹配,并删除第一个匹配项


//往集合里面添加元素时,他们在集合中的顺序会按照键值的降序排列

using System;
using System.Collections;
namespace Kehai.Exam.SourceCode
{
    public class MyClass
    {
        static void Main()
        {
            Hashtable hashTable = new Hashtable();
            hashTable.Add(5, "张三");
            hashTable.Add(3, "李四");
            hashTable.Add(4, "王五");
            hashTable.Add(1, "陈六");
            hashTable.Add(2, "赵七");

            foreach (object value in hashTable.Values)
                Console.WriteLine(value);
        }
    }
}


 Try catch finally
 Try 后面必须跟一个catch 或 finally  且 finally 里不可以 return ,不可离开finally子句,finally 里的所有语句必须被执行


 抽象类里面可以有抽象方法,也可以有实例方法,接口里只能所有的成员都必须是未实现的,且接口里的成员不能有访问修饰符修饰,不能有字段

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值