I need to create a generic list of T by reflection and add item of T to it by invoke a method "Add", but I have error. this is my code:
public class myObject
{
public object FieldValue { get; set; }
public int ID_OpenField { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
Type type = typeof(List<myObject>);
var genericType = typeof(List<>).MakeGenericType(type);
var list = Activator.CreateInstance(genericType);
myObject obj = new myObject() { FieldValue = "TextObjectValue", ID_OpenField = 1 };
object[] o = new object[] { obj };
list.GetType().GetMethod("Add").Invoke(list, o);
}
the last line gives me this error:
System.ArgumentException: 'Object of type 'myObject' cannot be converted to type 'System.Collections.Generic.List`1[myObject]'.'
CodePudding user response:
You came pretty close, but MakeGenericType
is being called with the wrong arguments.
This will work:
Type type = typeof(List<myObject>);
Type[] typeArgs = { typeof(myObject) };
var genericType = typeof(List<>).MakeGenericType(typeArgs);
// your code: var genericType = typeof(List<>).MakeGenericType(type);
var list = Activator.CreateInstance(genericType);
myObject obj = new myObject() { FieldValue = "TextObjectValue", ID_OpenField = 1 };
object[] o = new object[] { obj };
list.GetType().GetMethod("Add").Invoke(list, o);
Refer to How to dynamically create generic C# object using reflection? for more information.
CodePudding user response:
Here you are creating a List<List<myObject>>
, because type
is List<myObject>
:
Type type = typeof(List<myObject>);
var genericType = typeof(List<>).MakeGenericType(type);
var list = Activator.CreateInstance(genericType);
You should be using typeof(myObject)
instead:
var genericType = typeof(List<>).MakeGenericType(typeof(myObject));
var list = Activator.CreateInstance(genericType);