【发布时间】:2015-09-12 00:37:15
【问题描述】:
嘿,这是我的第一个问题!我真的在为下面的这些代码苦苦挣扎:
我有这些课程:
public class Home {
public List<Parameter> Parameter { get; set; }
}
我也有这个规格的功能:
public static List<T> DataTableMapToList<T>(DataTable dtb)
{ ... }
在另一个类中,当我需要调用这些函数时,我需要传递我的类的类型,但我处于反射属性循环中:
public void Initialize(ref object retObject)
{
using (var db = this)
{
db.Database.Initialize(force: false);
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = sStoredProcedure;
try
{
// Run the sproc
db.Database.Connection.Open();
DbDataReader reader = cmd.ExecuteReader();
DataSet ds = new DataSet();
ds.EnforceConstraints = false;
ds.Load(reader, LoadOption.OverwriteChanges, sTables);
var propertys = GetGenericListProperties(retObject);
foreach (DataTable table in ds.Tables) {
foreach (var info in propertys)
{
if (info.Name == table.TableName)
{
Type myObjectType = info.PropertyType;
// Create an instance of the list
var list = Activator.CreateInstance(myObjectType);
var list2 = DataTableMapToList<???>(table).ToList();
//Where the variable myObjectType is the TYPE of the class where I need to pass on the ??? marker
info.SetValue(retObject, list, null);
}
}
}
}
finally
{
db.Database.Connection.Close();
}
}
}
在哪里: retObject -> Home 的一个实例; info -> 这是 Home.Parametro 属性;
我想通过反射动态设置属性。一切正常,无需调用具有泛型类型的函数。但我需要调用函数来正确填充属性。
我什么都试过了:
作为对象传递,然后尝试转换(我得到一个必须实现IConverter的错误);
尝试将我所有的代码(仅用于测试)放入 DataTableMapToList() 中,即使如此我还是遇到了对象转换错误;
为我的最终变量强制发送列表,但我再次遇到转换器错误。;
我不知道我是否足够清楚自己真正需要什么,但我花了大约 4 个小时寻找解决方案直到知道为止。
【问题讨论】:
标签: c# .net reflection generic-list