如何在通用列表中获取T的类型

时间:2013-06-29 10:00:05

标签: c# generics reflection types generic-list

我正在编写一个反映我的类的编辑器,并将它们转换为UI字段,让我通过更改UI中字段的值并保存它们来创建对象文件。

问题是当我使用通用列表时,编辑器构建器因为不知道列表中对象的类型而停止以反映它,它会一直将对象视为object

我只需要知道列表或字典中对象的类型以反映它。

守则:

class ListUIEditor<T> : BaseEditor where T : new()
{
    void BuildEditor()
    {
       Button addbutton = new Button("+");
       addbutton.Clicked += add_Event;

        for (int i = 0; i < ((List<T>)base.boundObject).Count; i++)
        {
            container = new Container();         
            ObjectUIEditor editor = new ObjectUIEditor("itemName",
                                                       ((List<T>)base.boundObject)[i], 
                                                       container);
            editor.buildEditor();
            itemsSubEditors.Add(i, editor);
        }
    }

    protected void add_Event(object sender, EventArgs e)
    {       
        T newObject = new T();          
        container = new Container();            
        ObjectUIEditor editor = new ObjectUIEditor("itemName", newObject, container);
        editor.buildEditor();           
        itemsBox.ShowAll();
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

Type type = listObj.GetType().GetGenericArguments()[0];

ref

相关问题