140

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

如果我有一个myclass可以容纳 a的对象,如果属性为空List<SomeClass>,有谁知道如何获取下面代码中的类型?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

4 回答 4

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

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

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}
于 2009-06-25T13:02:32.773 回答
23

给定一个我怀疑是某种 的对象,我IList<>如何确定它是什么IList<>

这是大胆的解决方案。它假定您有要测试的实际对象(而不是 a 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();

印刷

typeof(DateTime)
于 2012-11-28T15:33:22.640 回答
12

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

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

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

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

于 2009-06-25T13:52:29.070 回答
9

给定一个我怀疑是某种 的对象,我IList<>如何确定它是什么IList<>

这是一个可靠的解决方案。抱歉,C# 的自省 API 让这变得异常困难。

/// <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();

退货

True
typeof(Int32)
于 2012-11-28T15:20:36.770 回答