从对象泛型列表中获取属性值

本文关键字:获取 属性 列表 对象 泛型 | 更新日期: 2023-09-27 18:08:03

我试图从我的通用列表的属性中获得值,但我得到一个错误"T不包含....的定义"

 var values GetValues(Id);
 if (values != null)
        {
            CreateTable<Object>(values);
        }
/////
    private void CreateTable<T>(IList<T> array) 
    {
        foreach (item in array)
        {
          //Problem is here **** when trying to get item.tag
         var text = new TextBox(){ Text = item.Tag , ID = item.TagID.ToString() };
        }
    }

如何使它与泛型一起工作?感谢您的帮助

从对象泛型列表中获取属性值

为什么您期望某个任意T类型的对象具有TagTagID属性?这些属性在哪里定义?如果它们是在接口上定义的,比如

public interface IItem
{
    string Tag { get; }
    int TagID { get; }
}

则不需要泛型,可以将CreateTable重新定义为

private void CreateTable(IList<IITem> array)
{
    foreach (var item in array)
    {
        //Problem is here **** when trying to get item.tag
        var text = new TextBox(){ Text = item.Tag , ID = item.TagID.ToString() };
    }
}