How do I create a dynamic type List

前端 未结 4 1094
野趣味
野趣味 2020-12-09 11:47

I don\'t want my List to be of fixed type. Rather I want the creation of List to be dependent on the type of variable. This code doesn\'t work:

using System;         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 12:48

    I want type safety but I need dynamic type safety.

    If you mean you want runtime type-safety, you can create List using reflection (see usr's answer) or dynamic and then treat it as the non-generic IList.

    Using dynamic, it would look something like this:

    static List CreateListByExample(T obj)
    {
        return new List();
    }
    
    …
    
    object something = "Apple";
    
    IList list = CreateListByExample((dynamic)something);
    
    list.Add(something); // OK
    
    list.Add(42);        // throws ArgumentException
    

提交回复
热议问题