如何从具有非定义属性名称的数据行添加

本文关键字:数据 添加 list 属性 定义 | 更新日期: 2023-09-27 18:21:14

我的英语很差。

我想将类添加到列表类,但我不想定义属性名称。

前任。声明类

public class LSale
{
   public int id {get;set;}
   public string name {get;set}
}

旧代码

public DataTable dt = new DataTable();
public List<LSale> mLSale {get; set;}
foreach ( DataRow t in dt.Rows)
{
    mLSale.Add( new LSale { 
            id = Convert.ToInt32(t["id"].ToString()) , 
            name = = t["name"].ToString() });        
}

如何添加不定义 id 和名称字段的 LSale但从 LSale 类的属性或字段中查找。

示例(此代码不正确(

Type mType = typeof( LSale );    
LSale mSale = nil;
foreach ( DataRow t in dt.Rows )
{
   foreach( Propertyinfo mp in mType.GetProperties() )
   {
       mSale[mp].Value = t[mp].Value;
   }
   mLSale.Add( new mSale );
}

请帮忙。

如何从具有非定义属性名称的数据行添加<list>类

您可以使用反射

public T MapObjects<T, Y>(Y item)
        {
            T _item = Activator.CreateInstance<T>();
            foreach (PropertyInfo propertyInfo in typeof(Y).GetProperties())
            {
                if (typeof(T).GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public) != null)
                    typeof(T).GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public).SetValue(_item, propValue);
            }
            return _item;
        }
其中 T 是目标类型,

Y 是源类型,这里有一个条件,源和目标类型的属性名称必须相同。