C# - Get the item type for a generic list

前端 未结 9 1978
小鲜肉
小鲜肉 2020-12-05 06:15

What would be the best way of getting the type of items a generic list contains? It\'s easy enough to grab the first item in the collection and call .GetType(), but I can\'

9条回答
  •  有刺的猬
    2020-12-05 06:59

    What about this, its all static (e.g. no instances required), and fast (no loops, no usage of linq), and it is simple :) these work for collections:

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

    And a few simple unit tests:

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

    Notice the fact that there are two ways to look at this, one type may be returned by the indexer and an other type may be returned by the enumerator. The unit test do show both.

    Have fun, Frans.

    P.s. For enumerables:

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

    And for enumerator:

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

提交回复
热议问题