Create generic List with reflection

前端 未结 2 592
滥情空心
滥情空心 2020-12-19 09:53

I have a class with a property IEnumerable. How do I make a generic method that creates a new List and assigns that property?

2条回答
  •  借酒劲吻你
    2020-12-19 10:24

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApplication16
    {
        class Program
        {
            static IEnumerable Func()
            {
                yield return 1;
                yield return 2;
                yield return 3;
            }
    
            static List MakeList()
            {
                return (List)Activator.CreateInstance(typeof(List), Func());
            }
    
            static void Main(string[] args)
            {
                foreach(int i in MakeList())
                {
                    Console.WriteLine(i);
                }
            }
        }
    }
    

提交回复
热议问题