【发布时间】:2018-09-01 22:47:50
【问题描述】:
我试图想出一种方法,只需将表从 SQL Server 加载到类中,而无需告诉它任何内容。基本上,只需创建类并让它知道要加载什么,基于此。这是我目前所拥有的。
我的问题是,有什么方法可以避免对类型进行硬编码,调用 reader.readString, reader.readString。 readInt32等..基于FieldType?
private Int32? readInt32(SqlDataReader reader, string columnName)
{
Int32? result = null;
if (!reader.IsDBNull(reader.GetOrdinal(columnName)))
{
result = reader.GetInt32(reader.GetOrdinal(columnName));
};
return result;
}
public List<T> readTable(string table, string wherecls, string connStr)
{
List<T> result = new List<T>();
using (SqlConnection connection = new SqlConnection(connStr))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from " + table;
if (wherecls.Length > 0) command.CommandText += " where " + wherecls;
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Object i = Activator.CreateInstance(typeof(T));
System.Reflection.FieldInfo[] fieldInfoList = typeof(T).GetFields();
foreach (System.Reflection.FieldInfo f in fieldInfoList)
{
if (f.FieldType == typeof(string)) f.SetValue(i, readString(reader, f.Name));
if (f.FieldType == typeof(Int32)) f.SetValue(i, readInt32(reader, f.Name));
if (f.FieldType == typeof(Int16)) f.SetValue(i, readInt16(reader, f.Name));
if (f.FieldType == typeof(byte)) f.SetValue(i, readByte(reader, f.Name));
if (f.FieldType == typeof(short)) f.SetValue(i, readShort(reader, f.Name));
}
result.Add((T)i);
}
}
}
}
return result;
}
谢谢你, 丹·蔡斯
【问题讨论】:
-
如果你对反射技术感兴趣,你也可以给 Fastmember 的源码看看:github.com/mgravell/fast-member
-
@DanielB 这个问题的不同之处,我真的只是想知道如何摆脱中间所有不同的 if/then/SetValue。我几乎把整个方法都变成了通用的,除了这个,它让我很生气。
标签: c# .net reflection ado.net sqlclient