从对象通用列表中获取属性值c#

时间:2016-09-21 01:49:07

标签: c# generics

我正在尝试从我的通用列表的属性中获取值但是我收到错误“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() };

        }

    }

如何使其与泛型一起使用?感谢任何帮助

1 个答案:

答案 0 :(得分:1)

为什么您希望某个任意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() };
    }
}
相关问题