gpt4 book ai didi

c# - 如何将包含某些属性的自定义类类型的未知对象列表传递给方法?

转载 作者:太空宇宙 更新时间:2023-11-03 20:35:37 26 4
gpt4 key购买 nike

我正在制作一个带有访问 SQLCE 数据库方法的数据库帮助程序类。我想使用相同的方法来读取使用不同类的行,这些类包含与不同表中的字段匹配的属性。要使用的类是在运行时确定的,我想将包含类对象的列表传递给方法并获取属性名称并使用它们来读取数据库。会非常方便,因为我可以将它用于我所有的 (SQLCE-) 数据库。

(我更新了错误的代码,以便在这里提供解决方案)

    #region ReadData
///----------------------------------------------------------------------
/// <summary>
/// Reads datarows from database and adds them to list.
/// </summary>
/// <param name="data">List containing objects with properties.</param>
/// <param name="table">Table in database.</param>
/// <param name="search">Substring of SQL-statement that follows 'WHERE'.</param>
/// <param name="connect">Connectionstring.</param>
/// <returns>true if successfull</returns>
///----------------------------------------------------------------------
public static bool ReadData<T>(List<T> data, string table, string search, string connect) where T : class, new()
{
// Return if input id missing
if (data == null || table == "" || connect == "") return false;

// retrieve properties from Data
PropertyInfo[] propinf = typeof(T).GetProperties();

// Create string with SQL-statement
string fields = "";
// retrieve fields from propinf
foreach (PropertyInfo p in propinf)
{
fields += fields == "" ? p.Name : ", " + p.Name;
}
// create SQL SELECT statement with properties and search
string sql = "SELECT " + fields + " FROM " + table;
sql += search == "" ? "" : " WHERE " + search;

// Instantiate and open database
SqlCeConnection cn = new SqlCeConnection(connect);
if (cn.State == ConnectionState.Closed)
cn.Open();
data.Clear(); // just in case
try
{
SqlCeCommand cmd = new SqlCeCommand(sql, cn);
cmd.CommandType = CommandType.Text;
SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable);
if (rs.HasRows) // Only if database is not empty
{
while (rs.Read()) // read database
{
// instantiate single item of list Data
var dataitem = new T();
int ordinal = 0;
foreach (PropertyInfo p in propinf)
{
// read database and
PropertyInfo singlepropinf = typeof(T).GetProperty(p.Name);
ordinal = rs.GetOrdinal(p.Name);
singlepropinf.SetValue(dataitem, rs.GetValue(ordinal), null); // fill data item
}
data.Add(dataitem); // and add it to data.
}
}
else
{
MessageBox.Show("No records matching '" + search + "'!");
return false;
}
}
catch (SqlCeException sqlexception)
{
MessageBox.Show(sqlexception.Message, "SQL-error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
cn.Close();
}
return true;
}
#endregion

我有两个问题:

1) 如何传递未知类型的列表?到目前为止我找到的答案并没有帮助我解决这个问题。

2) 如何实例化未知类型类的对象(在编译时)以便将其添加到列表中而不导致编译错误?

非常感谢!

最佳答案

1:未知类型的列表可能是非泛型 IList , 或 ArrayList , 或 List<object>

2:Activator.CreateInstance(type)

或者,看看编写通用方法,理想情况下是这样的:

ReadData<T>(List<T> data, ...) where T : class, new()

并使用new T()创建新项目,和typeof(T)谈谈Type .使用通用方法,调用者提供 T - 通常是隐式的。请注意,不需要 ref在你的例子中。

关于c# - 如何将包含某些属性的自定义类类型的未知对象列表传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5174537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com