Casting List<object> to List at runtime

前端 未结 1 1125
故里飘歌
故里飘歌 2021-01-12 18:10

I \'m trying to build a DI container and I \'ve stumbled on to the following problem: I have a method that retrieves a list of registered instances for a given type and I wa

1条回答
  •  被撕碎了的回忆
    2021-01-12 18:44

    You could create a generic list like this:

    public virtual IList Retrieve(Type type)
    {
      // ...
      listType = typeof(List<>).MakeGenericType(new Type[] { type });
      IList list = (IList)Activator.CreateInstance(listType);
      // ...
      return list
    }
    

    this list can be casted to IList, because it is one.

    You could consider to use IEnumerable and Cast, but then you don't have an instance of a list. I don'^t know how important it is to have one.

    0 讨论(0)
提交回复
热议问题