ama*_*ha4 3 .net c# sql arraylist sqldatareader
我有以下代码,它采用SQL语句(字符串),将结果加载到ArrayList(organisationList),它是组织的集合:
public void FillDataGridView(DataGridView grid, string SQLCommand)
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = SQLCommand;
SqlDataReader dataReader = dataCommand.ExecuteReader();
while (dataReader.Read())
{
Organisation org = new Organisation();
org.OrganisationId = (int)dataReader["OrganisationId"];
org.OrganisationName = (string)dataReader["OrganisationName"];
organisationList.Add(org);
}
grid.DataSource = organisationList;
dataReader.Close();
}
Run Code Online (Sandbox Code Playgroud)
我想调整此方法以填充传入其中的ArrayList.
我是否可以将列表传递给方法,并具有以下内容:
public void FillArrayList(DataGridView grid, SqlDataReader reader, ArrayList list)
{
//Fill the list with the contents of the reader
while (reader.Read())
{
Object obj = new Object
for(int i; i = 0; i < obj.NoOfProperties)
{
obj.Property[i] = reader[i];
}
list.Add(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
对不起,如果这有点模糊,我对OOP很新,有点迷失!
编辑:根据Darren Davies的建议,我修改了方法如下:
public void FillArrayList<T>(DataGridView grid, SqlDataReader reader, List<T> list)
{
//Fill the list with the contents of the reader
while (reader.Read())
{
Object obj = new Object();
Type type = typeof(T);
FieldInfo[] fields = type.GetFields(); // Get the fields of the assembly
int i = 0;
foreach(var field in fields)
{
field.SetValue(obj, reader[i]); // set the fields of T to the reader's value
// field.setValue(obj, reader[field.Name]); // You can also set the field value to the explicit reader name, i.e. reader["YourProperty"]
i++;
}
list.Add((T)obj);
}
grid.DataSource = list;
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,在将对象转换为类型T时出现错误:
无法将类型为"System.Object"的对象强制转换为"TestHarness.Organisation".
我的印象是Object可以存储任何东西.任何人都可以告诉我为什么这个演员阵容无法演出?
谢谢,
安迪
除非您使用的是.NET 1.1,否则您可能不应该使用它ArrayList; 通用List<T>是优选的.
您无法添加成员object- 它不可扩展.您需要知道要创建的对象的类型.泛型将是一个合理的对象.但是,为了节省你一些时间,你可能会看看精致:
var list = dataConnection.Query<YourType>(SQLCommand).ToList();
Run Code Online (Sandbox Code Playgroud)
使用直接列名到成员名称映射,将执行所有操作.您需要创建一个YourType具有您期望的属性(适当类型)的类.
如果你使用的是4.0,那么dapper也支持dynamic:
var list = dataConnection.Query(SQLCommand).ToList();
Run Code Online (Sandbox Code Playgroud)
这样使用dynamic,所以你仍然可以(不声明类型):
foreach(var obj in list) {
Console.WriteLine(obj.OrganisationId);
Console.WriteLine(obj.OrganisationName);
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,dynamic如果数据的使用距离非常接近,我只会使用这种方法.对于从方法返回,通用方法是优选的.同样,dynamic也不适合DataGridView.
最后,我注意到没有参数; 你总是想使用参数而不是连接.Dapper也支持这个:
string foo = ...;
var list = dataConnection.Query<YourType>(
"select * from SomeTable where Foo = @foo", new { foo }).ToList();
Run Code Online (Sandbox Code Playgroud)