Adding items to List using reflection

前端 未结 3 1824
旧巷少年郎
旧巷少年郎 2020-12-14 10:21

I was trying to add items to IList through reflection, but while calling the \"Add\" method an error was thrown \"object ref. not set\". While debugging I came to know that

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 10:59

    You have only created a generic type, you haven't created an instance of the type. You have a list type, but you don't have a list.

    The Result variabled contains a Type object, so Result.Gettype() returns the same as typeof(Type). You are trying to find an Add method in the Type class, not your list class.

    Could you not use generics instead of reflection, e.g.:

    public static List CreateListAndAddEmpty() where T : new() {
      List list = new List();
      list.Add(new T());
      return list;
    }
    

提交回复
热议问题