C#属性SetValue无法处理泛型列表类型
在我的WinForm应用程序中,我实际上使用了C#属性SetValue无法处理泛型列表类型,c#,winforms,generics,system.reflection,setvalue,C#,Winforms,Generics,System.reflection,Setvalue,在我的WinForm应用程序中,我实际上使用了LightweightDAL项目,它提供了一种很好的方法来填充我的数据模型。除了设置为另一个模型的列表的特性外,其他特性都可以正常工作。这是我的模型课: public class SchedaFamiglia { [DBField("Id")] public int Id { get; set; } [DBField("IdFamiglia")] public int IdFamiglia { get; set; }
LightweightDAL
项目,它提供了一种很好的方法来填充我的数据模型。除了设置为另一个模型的列表的特性外,其他特性都可以正常工作。这是我的模型课:
public class SchedaFamiglia
{
[DBField("Id")]
public int Id { get; set; }
[DBField("IdFamiglia")]
public int IdFamiglia { get; set; }
[DBField("IdMamma")]
public int IdMamma { get; set; }
[DBField("IdPapa")]
public int IdPapa { get; set; }
[DBField("IdBambino")]
public List<SchedaBambino> Figli { get; set; }
public SchedaFamiglia()
{
}}
不幸的是,上面的方法无法处理泛型列表,我不知道如何实现
有人能帮我吗?你说的“不能处理泛型列表”是什么意思?(您所拥有的也不是整个方法?)为什么
项
变量有用?编辑:对不起,是否退货项目代码>基本上我无法将属性“Figli”填充为datamodel SchedaBanbino的列表。该方法似乎只处理基本数据类型,而不处理集合。我正在试图找出如何处理收集。@Ras:请注意术语。收藏!=泛型,实际上正好相反。@Ras-您希望列表项如何存储在数据库中?你们有单独的餐桌吗?SchedaFamiglia中应该存储什么?
private static T GetItemFromReader<T>(IDataReader rdr) where T : class
{
Type type = typeof(T);
T item = Activator.CreateInstance<T>();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
// for each property declared in the type provided check if the property is
// decorated with the DBField attribute
if (Attribute.IsDefined(property, typeof(DBFieldAttribute)))
{
DBFieldAttribute attrib = (DBFieldAttribute)Attribute.GetCustomAttribute(property, typeof(DBFieldAttribute));
if (Convert.IsDBNull(rdr[attrib.FieldName])) // data in database is null, so do not set the value of the property
continue;
if (property.PropertyType == rdr[attrib.FieldName].GetType()) // if the property and database field are the same
property.SetValue(item, rdr[attrib.FieldName], null); // set the value of property
else
{
// change the type of the data in table to that of property and set the value of the property
property.SetValue(item, Convert.ChangeType(rdr[attrib.FieldName], property.PropertyType), null);
}
}
}