是否可以创建一个 SqlConnection 数组?例如;
SqlConnection[] con = new SqlConnection[4];
con[0].ConnectionString = "my connection string";
编写此代码时它没有错误,但是当您运行它时它会说:
Object reference not set to an instance of an object.
是否可以创建一个 SqlConnection 数组?例如;
SqlConnection[] con = new SqlConnection[4];
con[0].ConnectionString = "my connection string";
编写此代码时它没有错误,但是当您运行它时它会说:
Object reference not set to an instance of an object.
您没有分配数组列表中的对象,它应该是
con[0] = new SqlConnection("my connection string");
此外,当你写作时,
var con = new SqlConnection[4];
这并不意味着您已经创建了SqlConnection的四个新对象,而是说明创建了一个Array对象,该对象将持有对四个SqlConnection对象的引用。
因此,为了首先存储对象,您需要创建它们,然后将它们分配给 Array。
例子
con[0] = new SqlConnection("my connection string 1");
con[1] = new SqlConnection("my connection string 2");
con[2] = new SqlConnection("my connection string 3");
con[3] = new SqlConnection("my connection string 4");
var con = new SqlConnection[4];
con[0] = new SqlConnection("my connection string");
后:
SqlConnection[] con = new SqlConnection[4];
这个...
con[0].ConnectionString = "my connection string";
..相当于:
SqlConnection con; // Type defined, but no instance!
con.ConnectionString;
你想要的是相当于:
SqlConnection con = new SqlConnection();
// Accessible, since you now have an instance:
con.ConnectionString = "some string";
在你的情况下:
var con = new SqlConnection[4];
con[0] = new SqlConnection();
con[0].ConnectionString = "my connection string"