列表中包含带有属性Info的列表数据表扩展名



我正在使用数据表扩展从数据表转换到列表。在这里,当我试图添加一行到一个正常的列表属性,其工作良好。但是当我在列表中使用列表时,我遇到了问题。我无法设置属性中的值。

 private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            if (property.Name.Equals("ProductSpec"))
            {
                Type t = property.GetType();
                //  i am getting error when i am trying to do this
                property.SetValue(item, ProductSpecIteration(property, row), null);
            }
            if (row.Table.Columns.Contains(property.Name))
            {                   
                property.SetValue(item, row[property.Name] == DBNull.Value?"":row[property.Name], null);
            }
        }
        return item;
    }

 private static ProductSpec ProductSpecIteration(PropertyInfo property, DataRow row)
    {            
        ProductSpec lstProductSpec = new ProductSpec();
        lstProductSpec.product_specs_id = Convert.ToInt64(row["product_specs_id"]);            
        return lstProductSpec;
    }

我一般不能这样做。但即使我不能在这个扩展中添加这个?谁能帮我解决这个问题?

您正在尝试转换从DataRow返回的对象。Item[string]属性,不能直接设置。

string value = row[property.Name] == DBNull.Value?"":row[property.Name].ToString();
property.SetValue(item, Convert.ChangeType(value, property.PropertyType), null);

对于你可以使用的ProductSpec,

  ProductSpec spec = ProductSpecIteration(property, row);
  property.SetValue(item, Convert.ChangeType(spec , property.PropertyType), null);

但是,它不需要改变类型就可以正常工作,因为类型与属性类型

相同。

希望这对你有帮助。你可以在这里读到更多你也可以在这里阅读更多关于IConvertible Interface

IConvertible接口帮助返回必需的值,因为对象没有实现IConvertible,因此无法获得属性类型所需格式的值

最新更新