首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#泛型列表<T>如何获取T的类型?

C#泛型列表<T>如何获取T的类型?
EN

Stack Overflow用户
提问于 2009-06-25 12:57:39
回答 1查看 160K关注 0票数 140

我正在做一个反射项目,现在我被卡住了。

如果我有一个可以保存List<SomeClass>myclass对象,如果myclass.SomList属性为空,谁知道如何获得下面代码中的类型?

代码语言:javascript
复制
List<myclass> myList = dataGenerator.getMyClasses();
lbxObjects.ItemsSource = myList; 
lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;

private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Reflect();
}

Private void Reflect()
{
    foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())
    {
        switch (pi.PropertyType.Name.ToLower())
        {
            case "list`1":
            {           
                // This works if the List<T> contains one or more elements.
                Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));

                // but how is it possible to get the Type if the value is null? 
                // I need to be able to create a new object of the type the generic list expect. 
                // Type type = pi.getType?? // how to get the Type of the class inside List<T>?
                break;
            }
        }
    }
}

private Type GetGenericType(object obj)
{
    if (obj != null)
    {
        Type t = obj.GetType();
        if (t.IsGenericType)
        {
            Type[] at = t.GetGenericArguments();
            t = at.First<Type>();
        } 
        return t;
    }
    else
    {
        return null;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2009-06-25 13:52:29

Marc的回答是我使用的方法,但为了简单(以及更友好的API?)如果您有一个属性,可以在集合基类中定义一个属性,例如:

代码语言:javascript
复制
public abstract class CollectionBase<T> : IList<T>
{
   ...

   public Type ElementType
   {
      get
      {
         return typeof(T);
      }
   }
}

我发现这种方法很有用,对于任何泛型的新手来说都很容易理解。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1043755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档