C#通用列表<t>如何获取T的类型?</t>

时间:2009-06-25 12:57:39

标签: c# reflection generic-list

我正在做一个反思项目,现在我被卡住了。 如果我有一个可以容纳List的“myclass”对象 如果属性myclass.SomList为空,有没有人知道如何获取下面代码中的类型?

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;
            }
        }

4 个答案:

答案 0 :(得分:206)

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

更一般地说,要支持任何IList<T>,您需要检查接口:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

答案 1 :(得分:20)

鉴于我怀疑某个对象是某种IList<>,我如何确定 <{1}}

这是勇敢的解决方案。它假设您有要测试的实际对象(而不是IList<>)。

Type

使用示例:

public static Type ListOfWhat(Object list)
{
    return ListOfWhat2((dynamic)list);
}

private static Type ListOfWhat2<T>(IList<T> list)
{
    return typeof(T);
}

打印

object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();

答案 2 :(得分:8)

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

public abstract class CollectionBase<T> : IList<T>
{
   ...

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

我发现这种方法很有用,而且很容易理解任何新手的仿制药。

答案 3 :(得分:6)

鉴于我怀疑某个对象是某种IList<>,我如何确定 <{1}}

这是一个可靠的解决方案。我对长度表示道歉 - C#的内省API让人感到非常困难。

IList<>

使用示例:

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

返回

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();
相关问题