How to call extension method “ElementAt”of List with reflection?

前端 未结 4 1958
清歌不尽
清歌不尽 2020-12-19 07:00

I have problem that after creating object \"oListType01\" of type List < MyClass01 > and after assigning it to the another objet \"oObjectType \" of type \"object\" I ca

4条回答
  •  抹茶落季
    2020-12-19 07:24

    If we can safely assume that:

    • oObjectType is a IEnumerable of some T

    then here's the code to extract the items from it.

    Note that I seriously wonder if this is the right way to go about this, but you haven't given us enough information to help you figure out if there's a better way, so all we're left with is just answering the question as asked.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Diagnostics;
    
    namespace ConsoleApplication2
    {
        class MyClass01
        {
            public String _ID;
    
            public override string ToString()
            {
                return _ID;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                MyClass01 oMy1 = new MyClass01();
                oMy1._ID = "1";
    
                MyClass01 oMy2 = new MyClass01();
                oMy2._ID = "3";
    
                IList oListType01 = new List();
    
                oListType01.Add(oMy1);
                oListType01.Add(oMy2);
    
                object oObjectType = new object();
    
                oObjectType = oListType01;
    
                Test(oObjectType);
    
                Console.In.ReadLine();
            }
    
            private static void Test(object oObjectType)
            {
                Type tObject = oObjectType.GetType();
                Debug.Assert(tObject.IsGenericType);
                Debug.Assert(tObject.GetGenericArguments().Length == 1);
                Type t = tObject.GetGenericArguments()[0];
    
                Type tIEnumerable = typeof(IEnumerable<>).MakeGenericType(t);
                Debug.Assert(tIEnumerable.IsAssignableFrom(tObject));
    
                MethodInfo mElementAt =
                    typeof(Enumerable)
                    .GetMethod("ElementAt")
                    .MakeGenericMethod(t);
    
                Console.Out.WriteLine("o[0] = " +
                    mElementAt.Invoke(null, new Object[] { oObjectType, 0 }));
                Console.Out.WriteLine("o[1] = " +
                    mElementAt.Invoke(null, new Object[] { oObjectType, 1 }));
            }
        }
    }
    

提交回复
热议问题