繁体   English   中英

C# - 获取通用列表的项目类型

[英]C# - Get the item type for a generic list

获取通用列表包含的项目类型的最佳方法是什么? 获取集合中的第一个项目并调用 .GetType() 很容易,但我不能总是确定集合中会有一个项目。

希望这是有道理的。

谢谢,
桑尼

为此,您可以使用Type.GetGenericArguments方法。

List<Foo> myList = ...

Type myListElementType = myList.GetType().GetGenericArguments().Single();

对于更强大的方法:

public static Type GetListType(object someList)
{
    if (someList == null)
        throw new ArgumentNullException("someList");

    var type = someList.GetType();

    if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(List<>))
        throw new ArgumentException("Type must be List<>, but was " + type.FullName, "someList");

    return type.GetGenericArguments()[0];
}

但是如果你的变量类型是List<T>那么你可以使用typeof(T) 例如:

public static Type GetListType<T>(List<T> someList)
{
    return typeof(T);
}

请注意,您甚至不需要someList参数。 如果您已经在通用方法中,此方法只是一个如何使用typeof的示例。 如果您无权访问T令牌(列表存储在非泛型类型变量中,例如一个类型化的IListobject等),则只需要使用反射方法。

list.GetType().GetGenericArguments()[0]

这是另一种适用于非通用集合的方法:

static Type GetItemType(Type collectionType)
{
    return collectionType.GetMethod("get_Item").ReturnType;
}

即获取foo[x]的返回类型,其中foo是指定类型。

例子:

// Generic type; prints System.Int32
Console.WriteLine(GetItemType(typeof(List<int>)));

// Non-generic type; prints System.String
Console.WriteLine(GetItemType(typeof(System.Collections.Specialized.StringCollection)));

GetItemType上面的GetItemType方法有几个问题:

  • 如果类型没有索引运算符,它会抛出NullReferenceException

  • 如果该类型具有索引运算符的多个重载(例如this[string]this[int] ),它将抛出AmbiguousMatchException

这是一个更精致的版本:

public static Type GetItemType(this Type collectionType)
{
    var types =
        (from method in collectionType.GetMethods()
         where method.Name == "get_Item"
         select method.ReturnType
        ).Distinct().ToArray();
    if (types.Length == 0)
        return null;
    if (types.Length != 1)
        throw new Exception(string.Format("{0} has multiple item types", collectionType.FullName));
    return types[0];
}

怎么样,它都是静态的(例如不需要实例)和快速(没有循环,没有使用 linq),而且很简单 :) 这些适用于集合:

    [System.Diagnostics.DebuggerHidden]
    public static Type GetIndexedType(this ICollection poICollection)
    {
        PropertyInfo oPropertyInfo = poICollection == null ? null : poICollection.GetType().GetProperty("Item");
        return oPropertyInfo == null ? null : oPropertyInfo.PropertyType;
    }

    [System.Diagnostics.DebuggerHidden]
    public static Type GetEnumeratedType(this ICollection poICollection)
    {
        PropertyInfo oPropertyInfo = poICollection == null ? null : poICollection.GetType().GetMethod("GetEnumerator").ReturnType.GetProperty("Current");
        return oPropertyInfo == null ? null : oPropertyInfo.PropertyType;
    }

以及一些简单的单元测试:

        [Test]
        public void GetIndexedType()
        {
            Assert.AreEqual(null, ((ICollection)null).GetIndexedType());
            Assert.AreEqual(typeof(int), (new List<int>()).GetIndexedType());
            Assert.AreEqual(typeof(bool), (new SortedList<string, bool>()).GetIndexedType());
        }

        [Test]
        public void GetEnumeratedType()
        {
            Assert.AreEqual(null, ((ICollection)null).GetEnumeratedType());
            Assert.AreEqual(typeof(int), (new List<int>()).GetEnumeratedType());
            Assert.AreEqual(typeof(KeyValuePair<string, bool>), (new SortedList<string, bool>()).GetEnumeratedType());
        }

请注意,有两种方法可以查看这一点,一种类型可能由索引器返回,另一种类型可能由枚举器返回。 单元测试确实显示了两者。

玩得开心,弗兰斯。

Ps 对于枚举:

    [System.Diagnostics.DebuggerHidden]
    public static Type GetEnumeratedType(this System.Collections.IEnumerable poIEnumerable)
    {
        PropertyInfo oPropertyInfo = poIEnumerable == null ? null : poIEnumerable.GetType().GetMethod("GetEnumerator").ReturnType.GetProperty("Current");
        return oPropertyInfo == null ? null : oPropertyInfo.PropertyType;
    }

对于枚举器:

    [System.Diagnostics.DebuggerHidden]
    public static Type GetEnumeratedType(this System.Collections.IEnumerator poIEnumerator)
    {
        PropertyInfo oPropertyInfo = poIEnumerator == null ? null : poIEnumerator.GetType().GetProperty("Current");
        return oPropertyInfo == null ? null : oPropertyInfo.PropertyType;
    }
    public Type GetType(IEnumerable<object> resultList)
    {
        return resultList.GetType().GetElementType();
    }

老问题新方法dynamic

void Foo(){
   Type type GetTypeT(data as dynamic);
}

private static Type GetTypeT<T>(IEnumerable<T> data)
{
    return typeof(T);
}

这是一个也适用于派生类的解决方案。

因为有了这个类:

  public class SubList : List<int>
  {   }

如果您调用: subList.GetType().GetGenericArguments().Single()

它会抛出一个System.InvalidOperationException

使用这种方法,它适用于派生类:

public Type GetListItemType<T>(List<T> list)
{
  Type type = list.GetType();
  while (type != typeof(List<T>))
    type = type.BaseType;
  return type.GetGenericArguments().Single();
}


var list = new List<int>();
var subList = new SubList();
Console.WriteLine(GetListItemType(list)); // System.Int32
Console.WriteLine(GetListItemType(subList)); // System.Int32
Public Shared Function ListItemType(ListType As System.Type) As System.Type

  If Not ListType.IsGenericType Then
    If ListType.BaseType IsNot Nothing AndAlso ListType.BaseType.IsGenericType Then
      Return ListItemType(ListType.BaseType)
    End If
  Else
    Return ListType.GetGenericArguments.Single
  End If
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM